gpt4 book ai didi

python - 运算符(operator) 'is' 与方法的非常奇怪的行为

转载 作者:IT老高 更新时间:2023-10-28 20:34:30 25 4
gpt4 key购买 nike

为什么第一个结果是False,不应该是True吗?

>>> from collections import OrderedDict
>>> OrderedDict.__repr__ is OrderedDict.__repr__
False
>>> dict.__repr__ is dict.__repr__
True

最佳答案

对于用户定义的函数,在 Python 2 中,unboundbound 方法是通过 descriptor protocol 按需创建的。 ; OrderedDict.__repr__ 就是这样一个方法对象,因为被包装的函数被实现为 pure-Python function .

描述符协议(protocol)将调用 __get__ method在支持它的对象上,因此每当您尝试访问 OrderedDict.__repr__ 时都会调用 __repr__.__get__();对于类None(无实例)和类对象本身传入。因为每次函数__get__方法都会得到一个new方法对象被调用,is 失败。不是同一个方法对象。

dict.__repr__ 不是自定义 Python 函数而是 C 函数,其 __get__ 描述符方法essentially just returns self when accessed on the class .每次访问该属性都会为您提供相同的对象,因此 is 有效:

>>> dict.__repr__.__get__(None, dict) is dict.__repr__  # None means no instance
True

方法有一个 __func__ 属性引用被包装的函数,用它来测试身份:

>>> OrderedDict.__repr__
<unbound method OrderedDict.__repr__>
>>> OrderedDict.__repr__.__func__
<function __repr__ at 0x102c2f1b8>
>>> OrderedDict.__repr__.__func__.__get__(None, OrderedDict)
<unbound method OrderedDict.__repr__>
>>> OrderedDict.__repr__.__func__ is OrderedDict.__repr__.__func__
True

Python 3 取消了 unbound 方法,function.__get__(None, classobj) 返回函数对象本身(因此它的行为类似于 dict.__repr__ 确实)。但是您会看到与 bound 方法相同的行为,即从实例中检索的方法。

关于python - 运算符(operator) 'is' 与方法的非常奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24367930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com