gpt4 book ai didi

python - 为什么 cls.__dict__[meth] 与类方法/静态方法的 getattr(cls, meth) 不同?

转载 作者:太空宇宙 更新时间:2023-11-04 02:48:06 26 4
gpt4 key购买 nike

我以前从未见过其他任何东西像这样工作。

还有其他的东西可以做到这一点吗?

>>> class NothingSpecial:
@classmethod
def meth(cls): pass

>>> NothingSpecial.meth
<bound method classobj.meth of <class __main__.NothingSpecial at 0x02C68C70>>
>>> NothingSpecial.__dict__['meth']
<classmethod object at 0x03F15FD0>

>>> getattr(NothingSpecial, 'meth')
<bound method NothingSpecial.meth of <class '__main__.NothingSpecial'>>

>>> object.__getattribute__(NothingSpecial, 'meth')
<classmethod object at 0x03FAFE90>

>>> type.__getattribute__(NothingSpecial, 'meth')
<bound method NothingSpecial.meth of <class '__main__.NothingSpecial'>>

最佳答案

Getattr 使用描述符逻辑

主要区别在于字典查找不进行额外处理,而属性获取包含额外逻辑(有关所有详细信息,请参阅我的 Descriptor How-To Guide)。

有两种不同的底层方法

1) 调用 NothingSpecial.__dict__['meth'] 使用方括号运算符分派(dispatch)给 dict.__getitem__ 进行简单的哈希表查找或引发 < em>KeyError 如果找不到。

2) 调用 NothingSpecial.meth 使用点运算符分派(dispatch)给 type.__getattribute__ 进行简单查找,然后是 descriptors 的特例.如果查找失败,则会引发 AttributeError

它是如何工作的

整体逻辑记录在案herehere .

In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol: __get__(), __set__(), and/or __delete__(). If any of those methods are defined for an object, it is said to be a descriptor.

The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, a.x has a lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses.

However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined and how they were called

希望您发现所有这些对您有所帮助。您正在进行的探索是学习 Python 的好方法:-)

附言您可能还喜欢阅读 Python 2.2 中的原始 Whatsnew entry for descriptors或查看 PEP 252 Guido van Rossum 最初提出这个想法的地方。

关于python - 为什么 cls.__dict__[meth] 与类方法/静态方法的 getattr(cls, meth) 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44596009/

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