Why check if cls is the class in __subclasshook__?

不羁的心 提交于 2019-12-22 05:14:38

问题


In the Python standard library documentation, the example implementation of __subclasshook__ is:

class MyIterable(metaclass=ABCMeta):

[...]

@classmethod
def __subclasshook__(cls, C):
    if cls is MyIterable:
        if any("__iter__" in B.__dict__ for B in C.__mro__):
            return True
    return NotImplemented

CPython's implementation of collections.abc indeed follows this format for most of the __subclasshook__ member functions it defines. What is the purpose of explicitly checking the cls argument?


回答1:


__subclasshook__ is inherited. The cls is MyIterable check ensures that concrete subclasses of MyIterable use the regular issubclass logic instead of checking for an __iter__ method. Otherwise, for a class MyConcreteIterable(MyIterable), you would have issubclass(list, MyConcreteIterable) returning True.



来源:https://stackoverflow.com/questions/35858285/why-check-if-cls-is-the-class-in-subclasshook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!