我测试了这个简单的代码,发现使我困惑的地方.在Python 3.6中运行以下代码,两个语句均返回True.为什么?
import typing
print(issubclass(list, typing.List)) # print True
print(issubclass(typing.List, list)) # print True
有人可以给我一些解释吗?
解决方法:
严格来说,列表不是type.List的子类.要查看列表实际上是其子类的列表,可以看一下它的MRO:
>>> list.__mro__
(<class 'list'>, <class 'object'>)
另一方面,typeing.List的MRO显示它实际上是list以及许多其他类的子类:
>>> typing.List.__mro__
(typing.List, <class 'list'>, typing.MutableSequence, <class 'collections.abc.MutableSequence'>, typing.Sequence, <class 'collections.abc.Sequence'>, typing.Reversible, <class 'collections.abc.Reversible'>, typing.Collection, <class 'collections.abc.Collection'>, <class 'collections.abc.Sized'>, typing.Iterable, <class 'collections.abc.Iterable'>, typing.Container, <class 'collections.abc.Container'>, typing.Generic, <class 'object'>)
那么,为什么Python会说列表是type.List的子类?
好吧,这就是键入.List的重点.假装成列表的基类.
怎么做?
使用抽象基类.看看Python doc对他们的评价:
ABCs introduce virtual subclasses, which are classes that don’t
inherit from a class but are still recognized by isinstance() and
issubclass(); see the 07002 module documentation.
您可以从其MRO中看到type.List是从许多ABC继承的,该列表将其识别为基类,例如:
>>> issubclass(list, collections.abc.MutableSequence)
True
>>> issubclass(list, collections.abc.Collection)
True
>>> issubclass(list, collections.abc.Container)
True