__abstractmethods__和AttributeError
dir()
当我注意到这一点时,我正在使用内置函数:
>>> dir(type)
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__text_signature__', '__weakrefoffset__', 'mro']
>>> type.__abstractmethods__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __abstractmethods__
>>> list.__abstractmethods__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __abstractmethods__
我不明白,它出现在列表中,为什么会出现这样的错误?
-
__abstractmethods__
是支持抽象基类的描述符;
它包装了默认情况下为空的 插槽
(因此描述符会引发属性错误)。最重要的是,它是CPython处理抽象方法的实现细节。
__该属性用于跟踪抽象的方法,因此,如果实例未提供具体的实现,则可以阻止实例的创建:
>>> import abc >>> class FooABC(metaclass=abc.ABCMeta): ... @abc.abstractmethod ... def bar(self): ... pass ... >>> FooABC.__abstractmethods__ frozenset({'bar'}) >>> class Foo(FooABC): pass ... >>> Foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class Foo with abstract methods bar
该
abc.ABCMeta
实现将设置__abstractmethods__
属性,并type()
使用它来检查应该已经实现但尚未实现的任何抽象方法。