哪种特殊方法在Python中绕过__getattribute__?
作者:互联网
In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the
__getattribute__()
method even of the object’s metaclass.
The docs提到了__hash __,__repr__和__len__等特殊方法,我从经验中知道它还包含Python 2.7的__iter__.
引用an answer to a related question:
“Magic
__methods__()
are treated specially: They are internally assigned to “slots” in the type data structure to speed up their look-up, and they are only looked up in these slots.”
为了改进我对another question的回答,我需要知道:具体来说,我们在谈论哪些方法?
解决方法:
您可以在python3 documentation中找到对象.__ getattribute__的答案,其中说明:
Called unconditionally to implement attribute accesses for instances of the class. If the class also defines
__getattr__()
, the
latter will not be called unless__getattribute__()
either calls it
explicitly or raises an AttributeError. This method should return the
(computed) attribute value or raise an AttributeError exception. In
order to avoid infinite recursion in this method, its implementation
should always call the base class method with the same name to access
any attributes it needs, for example, object.__getattribute__(self,
.
name)Note
This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in
functions. See Special method lookup.
this页面也解释了这种“机械”的工作原理.只有在使用.(点)运算符(以及Zagorulkin指出的hasattr)访问属性时,才会调用__getattribute__.
请注意,页面没有指定隐式查找哪些特殊方法,因此我认为这适用于所有这些方法(您可能会找到here.
标签:python,magic-methods 来源: https://codeday.me/bug/20190926/1818410.html