How are arguments passed to a function through __getattr__

纵然是瞬间 提交于 2019-12-02 20:58:07

You are not printing 20 in your __getattr__ function. The function finds the make_statement attribute on the Child instance and returns that. As it happens, that attribute is a method, so it is callable. Python thus calls the returned method, and that method then prints 20.

If you were to remove the () call, it would still work; we can store the method and call it separately to get 20 printed:

>>> 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 to see the arguments, you'd have to return a wrapper function instead:

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)

This now results in:

>>> person.make_statement(20)
Calling __getattr__: make_statement
called with (20,) and {}
I am an instance of Child with age 20
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!