在Python的抽象类中是否存在一些用于强制嵌套接口的机制?

问题描述 投票:1回答:1

我想创建一个具有嵌套类的类,该类在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 inner-classes abc
1个回答
0
投票

这应该可以解决问题:

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
© www.soinside.com 2019 - 2024. All rights reserved.