我以前从未见过其他任何东西像这样工作。
还有其他的东西可以做到这一点吗?
>>> 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。
它是如何工作的
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 最初提出这个想法的地方。
