英文:
dict_items class not showing correct class inheritance
问题
我在阅读这个答案时发现<class 'dict_items'>
是<class 'collections.abc.ItemsView'>
的一个子类。您可以使用以下代码进行测试:
>>> import collections
>>> issubclass({}.items().__class__, collections.abc.ItemsView)
True
然而,我进一步检查了<class 'dict_items'>
的__mro__
属性,由于它是<class 'collections.abc.ItemsView'>
的子类,当我打印__mro__
属性时应该显示出来,但它并不存在。
>>> {}.items().__class__.__mro__
(<class 'dict_items'>, <class 'object'>)
我还检查了<class 'collections.abc.ItemsView'>
的子类:
>>> collections.abc.ItemsView.__subclasses__()
[<class 'collections._OrderedDictItemsView'>]
有人能告诉我我为什么会得到这个结果吗?
英文:
I was going through this answer where I found that <class 'dict_items'>
is a subclass of <class 'collections.abc.ItemsView'>
. You can test this using:
>>> import collections
>>> issubclass({}.items().__class__, collections.abc.ItemsView)
True
However, I went a bit further and checked the __mro__
attribute of <class 'dict_items'>
and as this is a subclass of <class 'collections.abc.ItemsView'>
, it should be printed when I print the __mro__
attribute but it isn't there.
>>> {}.items().__class__.__mro__
(<class 'dict_items'>, <class 'object'>)
I also checked the subclasses of <class 'collections.abc.ItemsView'>
>>> collections.abc.ItemsView.__subclasses__()
[<class 'collections._OrderedDictItemsView'>]
Can anyone tell me why am I getting this?
答案1
得分: 3
ItemsView
将 DictItems
明确注册为其的“虚拟子类”,因此这是被检查的内容。
即使在某些情况下,类型没有被明确地 register
,issubclass
仍然可以报告一个类型是否是另一个类型的子类型,即使这在字面上并不成立。issubclass
并不一定告诉您一个东西是否是另一个东西的字面子类,因为这种行为可以被覆盖:
> 这些 ABCs 重写了 object.__subclasshook__()
以通过验证所需的方法是否存在来支持测试接口,并且这些方法没有被设置为 None。这仅适用于简单的接口。更复杂的接口需要注册或直接子类化。
英文:
ItemsView
explicitly registers DictItems
as a "virtual subclass" of it, so that's what's being checked here.
Even in cases where a type isn't register
ed explicitly though, issubclass
can still report that one type is a subtype of another even when that isn't literally true. issubclass
doesn't necessarily tell you if one thing is a literal subclass of another, since that behavior can be overridden:
> These ABCs override object.__subclasshook__()
to support testing an interface by verifying the required methods are present and have not been set to None. This only works for simple interfaces. More complex interfaces require registration or direct subclassing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论