__abstractmethods__和AttributeError

发布于 2021-01-29 16:56:12

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__

我不明白,它出现在列表中,为什么会出现这样的错误?

关注者
0
被浏览
35
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    __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()使用它来检查应该已经实现但尚未实现的任何抽象方法。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看