了解\uu getattribute__

2024-04-26 14:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

通过以上代码,我想实现以下行为:

>>>t = Test()
>>>t.a
1
>>>t._shadow.a = 17
>>>t.a
17
>>>t.b
2

代码可以工作,但它将打印“not shadowd”M次(直到达到递归深度)。问题是,为什么不应该涉及任何递归,我调用的是object.__getattribute__,而不是self.__getattribute__。你知道吗


Tags: 代码nametestselfreturnobjectdefnot
1条回答
网友
1楼 · 发布于 2024-04-26 14:14:59

__getattribute__用于all属性访问,包括self._shadow。但是,既然已经重写了__getattribute__,那么self._shadow就会触发无限递归。你知道吗

唯一的解决方法是使用object.__getattribute__或更好的super(Test, self).__getattribute__来检索_shadow属性:

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)

对shadow对象的属性访问不需要使用object.__getattribute__。不要使用Pokemon风格的异常处理(您不想全部捕获);在这里只捕获特定的AttributeError异常。你知道吗

演示:

>>> t = Test()
>>> t.a
not shadowed
1
>>> t._shadow.a = 42
not shadowed
>>> t.a
42

注意,在这里,访问t._shadow也会在__getattribute__处理程序中触发'not shadowed'消息。你知道吗

相关问题 更多 >