了解__getattribute__ [英] Understanding __getattribute__
问题描述
class Shadow(object):
pass
class Test(object):
a = 1
b = 2
_shadow = Shadow()
def __getattribute__(self, name):
try:
return object.__getattribute__(self._shadow, name)
except: print "not shadowed"
return object.__getattribute__(self, name)
通过上面这段code的,我想实现以下行为:
With the above piece of code I would like to implement the following behavior:
>>>t = Test()
>>>t.a
1
>>>t._shadow.a = 17
>>>t.a
17
>>>t.b
2
在code的作品,但它会打印没有影子M-次(直至达到递归深度)。问题是为什么,不应该有任何递归参与,我打电话对象.__的getAttribute __
,而不是自.__的getAttribute __
。
推荐答案
__的getAttribute __
被调用的所有属性的访问,其中包括 self._shadow
。但是,既然你有 __ __的getAttribute
覆盖 self._shadow
触发无限递归。
__getattribute__
is called for all attribute access, including for self._shadow
. But since you have __getattribute__
overridden, self._shadow
triggers an infinite recursion.
唯一的变通办法因为这是使用对象.__的getAttribute __
,或更好,超(测试,个体经营).__的getAttribute __
,检索 _shadow
属性:
The only work-around for that is to use object.__getattribute__
, or better, super(Test, self).__getattribute__
, to retrieve the _shadow
attribute:
class Test(object):
a = 1
b = 2
_shadow = Shadow()
def __getattribute__(self, name):
shadow = super(Test, self).__getattribute__('_shadow')
try:
return getattr(shadow, name)
except AttributeError:
print "not shadowed"
return super(Test, self).__getattribute__(name)
有没有必要使用对象.__的getAttribute __
的阴影对象的属性访问。不要使用口袋妖怪式的异常处理(你不想赶上他们全部);只捕获特定的 AttributeError的
例外这里。
There is no need to use object.__getattribute__
for the attribute access on the shadow object. Don't use Pokemon-style exception handling (you don't want to catch them all); catch only the specific AttributeError
exception here.
演示:
>>> t = Test()
>>> t.a
not shadowed
1
>>> t._shadow.a = 42
not shadowed
>>> t.a
42
请注意,这里也访问 t._shadow
,因为它不用通过触发'没有影子'
信息 __ __的getAttribute
处理程序。
Note that here too, accessing t._shadow
triggers the 'not shadowed'
message as it goes through the __getattribute__
handler.
这篇关于了解__getattribute__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!