你没有打印20
在你的__getattr__
功能。该函数找到make_statement
属性在 Child 实例上并返回该实例。碰巧,该属性是一个方法,因此它是可调用的。 Python 因此调用返回的方法,并且that方法然后打印20
.
如果您要删除()
打电话,它仍然可以工作;我们可以存储该方法并单独调用它来获取20
打印:
>>> person.make_statement
Calling __getattr__: make_statement
<bound method Child.make_statement of <__main__.Child instance at 0x10db5ed88>>
>>> ms = person.make_statement
Calling __getattr__: make_statement
>>> ms()
I am an instance of Child with age 10
If you have要查看参数,您必须返回一个包装函数:
def __getattr__(self, attr):
print("Calling __getattr__: "+attr)
if hasattr(self.child, attr):
def wrapper(*args, **kw):
print('called with %r and %r' % (args, kw))
return getattr(self.child, attr)(*args, **kw)
return wrapper
raise AttributeError(attr)
现在的结果是:
>>> person.make_statement(20)
Calling __getattr__: make_statement
called with (20,) and {}
I am an instance of Child with age 20