考虑以下代码示例(python 2.7):
class Parent:
def __init__(self, child):
self.child = child
def __getattr__(self, attr):
print("Calling __getattr__: "+attr)
if hasattr(self.child, attr):
return getattr(self.child, attr)
else:
raise AttributeError(attr)
class Child:
def make_statement(self, age=10):
print("I am an instance of Child with age "+str(age))
kid = Child()
person = Parent(kid)
kid.make_statement(5)
person.make_statement(20)
可以看出,函数调用通过's函数person.make_statement(20)
调用函数。在调用子实例中的相应函数之前,我可以在函数中打印出属性。到目前为止很清楚。Child.make_statement
Parent
__getattr__
__getattr__
但是调用的参数是如何person.make_statement(20)
通过的__getattr__
呢?如何在我的__getattr__
函数中打印出数字“20”?