什么时候应该从ABC继承?

Mar*_*oma 0 python abc

我一直认为,abc.ABC当不希望实例化该类时,应该继承该实例。但是我刚刚意识到,如果一门课程只有一门课,@abstractmethod那么它也无法实例化它。

还有其他继承的理由ABC吗?

che*_*ner 5

除非您abc.ABCMeta用作类的元类(无论是显式还是通过继承abc.ABC),abstractmethod否则使用using 不会真正起作用。

>>> from abc import abstractmethod, ABC
>>> class Foo:
...   @abstractmethod
...   def bar(self):
...     pass
...
>>> f = Foo()
>>>
Run Code Online (Sandbox Code Playgroud)

同样,ABCMeta除非您将至少一种方法标记为抽象,否则使用并不意味着什么:

>>> class Bar(ABC):
...     pass
...
>>> b = Bar()
>>>
Run Code Online (Sandbox Code Playgroud)

两者的结合使一个类(名义上)不可实例化:

>>> class Baz(ABC):
...   @abstractmethod
...   def m(self):
...     pass
...
>>> b = Baz()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Baz with abstract methods m
>>>
Run Code Online (Sandbox Code Playgroud)

(即使如此,也请注意,所有@abstractmethod操作都是在尝试实例化该类时将修饰的方法添加到元类机器要查询的集合中。这很容易使机器失败:

>>> Baz.__abstractmethods__
frozenset({'m'})
>>> Baz.__abstractmethods__ = set()
>>> b = Baz()
>>>
Run Code Online (Sandbox Code Playgroud)

)


注意,ABC它本身是一个琐碎的类,ABCMeta用作其元类,这使得其任何后代也都使用它。

# Docstring omitted; see
# https://github.com/python/cpython/blob/3.7/Lib/abc.py#L166
# for the original
class ABC(metaclass=ABCMeta):
    __slots__ = ()
Run Code Online (Sandbox Code Playgroud)