我想创建一个具有嵌套类的类,该类在Python中定义了一些协定。一个可靠的例子是一个类型化的配置对象。我对此的尝试如下:
from typing import Mapping
from abc import ABCMeta, abstractmethod
class BaseClass(metaclass=ABCMeta):
# If you want to implement BaseClass, you must also implement BaseConfig
class BaseConfig(metaclass=ABCMeta):
@abstractmethod
def to_dict(self) -> Mapping:
"""Converts the config to a dictionary"""
但是不幸的是,我可以在不实现BaseClass
的情况下实例化BaseConfig
的子类:
class Foo(BaseClass):
pass
if __name__ == "__main__":
foo = Foo()
是否有某种方法可以强制子类也必须实现内部类?
这应该可以解决问题:
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from typing import Mapping
>>> from abc import ABCMeta, abstractmethod
>>>
>>> class BaseClass(metaclass=ABCMeta):
... # If you want to implement BaseClass, you must also implement BaseConfig
... @abstractmethod
... class BaseConfig(metaclass=ABCMeta):
... @abstractmethod
... def to_dict(self) -> Mapping:
... """Converts the config to a dictionary"""
...
>>> class Foo(BaseClass):
... pass
...
>>> class Foo2(BaseClass):
... class BaseConfig():
... pass
...
>>> Foo2()
<__main__.Foo2 object at 0x7f4f259ac080>
>>>> Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Foo with abstract methods BaseConfig