了解__getattribute__ [英] Understanding __getattribute__

查看:181
本文介绍了了解__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-次(直至达到递归深度)。问题是为什么,不应该有任何递归参与,我打电话对象.__的ge​​tAttribute __ ,而不是自.__的ge​​tAttribute __

推荐答案

__的ge​​tAttribute __ 被调用的所有属性的访问,其中包括 self._shadow 。但是,既然你有 __ __的ge​​tAttribute 覆盖 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.

唯一的变通办法因为这是使用对象.__的ge​​tAttribute __ ,或更好,超(测试,个体经营).__的ge​​tAttribute __ ,检索 _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)

有没有必要使用对象.__的ge​​tAttribute __ 的阴影对象的属性访问。不要使用口袋妖怪式的异常处理(你不想赶上他们全部);只捕获特定的 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 ,因为它不用通过触发'没有影子'信息 __ __的ge​​tAttribute 处理程序。

Note that here too, accessing t._shadow triggers the 'not shadowed' message as it goes through the __getattribute__ handler.

这篇关于了解__getattribute__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆