在学习python3rd时,我看到了以下代码
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]
?在
没有使用原始参数执行返回函数的代码。在
wrapper
类没有.append
属性,因此Python返回到wrapper.__getattr__
方法。从^{包装的对象(带有
[1, 2, 3]
的列表对象)确实有一个append
属性(一个方法),因此getattr(self.wrapped, 'append')
返回它。在调用返回的方法,传入
4
,并将其附加到self.wrapped
list对象。在您可以自己轻松地复制这些步骤:
相关问题 更多 >
编程相关推荐