调用\u getattr\uu方法后

2024-09-30 14:33:59 发布

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

在学习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]?在

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


Tags: 方法代码selfreturnobjectinitdeftrace
1条回答
网友
1楼 · 发布于 2024-09-30 14:33:59

wrapper类没有.append属性,因此Python返回到wrapper.__getattr__方法。从^{} special method documentation

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).

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

调用返回的方法,传入4,并将其附加到self.wrappedlist对象。在

您可以自己轻松地复制这些步骤:

>>> 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]

相关问题 更多 >