python – 参数如何通过__getattr__传递给一个函数

前端之家收集整理的这篇文章主要介绍了python – 参数如何通过__getattr__传递给一个函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑下面的代码示例( python 2.7):
  1. class Parent:
  2. def __init__(self,child):
  3. self.child = child
  4.  
  5. def __getattr__(self,attr):
  6. print("Calling __getattr__: "+attr)
  7. if hasattr(self.child,attr):
  8. return getattr(self.child,attr)
  9. else:
  10. raise AttributeError(attr)
  11.  
  12. class Child:
  13. def make_statement(self,age=10):
  14. print("I am an instance of Child with age "+str(age))
  15.  
  16. kid = Child()
  17. person = Parent(kid)
  18.  
  19. kid.make_statement(5)
  20. person.make_statement(20)

可以显示,函数调用person.make_statement(20)通过Parent的__getattr__函数调用Child.make_statement函数.在__getattr__函数中,我可以在子实例的相应函数调用之前打印出属性.到目前为然这么清楚

但是调用person.make_statement(20)的参数怎么通过__getattr__?我可以在__getattr__函数中打印出数字“20”吗?

解决方法

你不是在__getattr__函数中打印20.该函数在Child实例上找到make_statement属性并返回.发生这种情况,该属性是一种方法,因此它是可调用的. Python因此调用返回方法,然后打印20.

如果你要删除()调用,它仍然可以工作;我们可以存储方法并单独打电话给20打印:

  1. >>> person.make_statement
  2. Calling __getattr__: make_statement
  3. <bound method Child.make_statement of <__main__.Child instance at 0x10db5ed88>>
  4. >>> ms = person.make_statement
  5. Calling __getattr__: make_statement
  6. >>> ms()
  7. I am an instance of Child with age 10

如果你必须看到参数,你必须返回一个包装函数

  1. def __getattr__(self,attr):
  2. print("Calling __getattr__: "+attr)
  3. if hasattr(self.child,attr):
  4. def wrapper(*args,**kw):
  5. print('called with %r and %r' % (args,kw))
  6. return getattr(self.child,attr)(*args,**kw)
  7. return wrapper
  8. raise AttributeError(attr)

现在这样做:

  1. >>> person.make_statement(20)
  2. Calling __getattr__: make_statement
  3. called with (20,) and {}
  4. I am an instance of Child with age 20

猜你在找的Python相关文章