在调用__getattr__方法之后

时间:2015-03-01 15:59:36

标签: python getattr

在学习Python第3版中,我看到了这段代码

class wrapper:
    def __init__(self, object):
        self.wrapped = object
    def __getattr__(self, attrname):
        print("Trace:", attrname)
        return getattr(self.wrapped, attrname)

x = wrapper([1,2,3])
x.append(4)
print(x.wrapped)

我想确切地知道调用此__getattr__方法后会发生什么,该方法只返回getattr方法。

为什么是最后一行[1, 2, 3, 4]的结果?

没有代码使用原始参数执行返回的函数。

1 个答案:

答案 0 :(得分:3)

wrapper类没有.append属性,因此Python回退到wrapper.__getattr__方法。来自object.__getattr__ special method documentation

  

当属性查找未在通常位置找到该属性时调用(即,它不是实例属性,也不在self的类树中找到。)

包装对象(带有[1, 2, 3]的列表对象)确实具有append属性(方法),因此getattr(self.wrapped, 'append')会返回它。

调用返回的方法,传入4,将其附加到self.wrapped列表对象。

您可以自己轻松地重现这些步骤:

>>> wrapped = [1, 2, 3]
>>> getattr(wrapped, 'append')
<built-in method append of list object at 0x107256560>
>>> getattr(wrapped, 'append')(4)
>>> wrapped
[1, 2, 3, 4]
相关问题