为什么要检查cls是否是__subclasshook__中的类? [英] Why check if cls is the class in __subclasshook__?

查看:166
本文介绍了为什么要检查cls是否是__subclasshook__中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python标准库文档中, __ subclasshook __ 的示例实现是:

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

对于大多数 __ subclasshook __ 成员,CPython的 collections.abc 的实现确实遵循这种格式。它定义的功能。
显式检查 cls 参数的目的是什么?

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?

推荐答案

__ subclasshook __ 被继承。 cls是MyIterable 检查可确保 MyIterable 的具体子类使用常规的 issubclass 逻辑,而不是检查 __ iter __ 方法。否则,对于 MyConcreteIterable(MyIterable)类,您将具有 issubclass(list,MyConcreteIterable)返回 True

__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.

这篇关于为什么要检查cls是否是__subclasshook__中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆