如何通过__getattr__将参数传递给函数

Ale*_*lex 12 python inheritance arguments function getattr

请考虑以下代码示例(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)
Run Code Online (Sandbox Code Playgroud)

可以证明,该函数调用person.make_statement(20)调用Child.make_statement通过函数Parent__getattr__功能.在__getattr__函数中,我可以在调用子实例中的相应函数之前打印出属性.到目前为止这么清楚.

但是这个呼叫的论点是如何person.make_statement(20)通过的__getattr__呢?我怎么能在我的__getattr__功能中打印出数字'20' ?

Mar*_*ers 21

您没有20__getattr__功能中打印.该函数在Child实例上查找该make_statement 属性并返回该属性.碰巧,该属性是一个方法,因此它是可调用的.Python因此调用返回的方法,然后方法打印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
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

现在这导致:

>>> person.make_statement(20)
Calling __getattr__: make_statement
called with (20,) and {}
I am an instance of Child with age 20
Run Code Online (Sandbox Code Playgroud)