dict_items类未显示正确的类继承。

huangapple go评论64阅读模式
英文:

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

ItemsViewDictItems 明确注册为其的“虚拟子类”,因此这是被检查的内容。

即使在某些情况下,类型没有被明确地 registerissubclass 仍然可以报告一个类型是否是另一个类型的子类型,即使这在字面上并不成立。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 registered 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.

huangapple
  • 本文由 发表于 2023年7月14日 05:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定