您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:22:51 python 字数 4548 阅读 549 来源 www.jb51.cc/python

考虑下面的代码示例( python 2.7): class Parent: def __init__(self, child): self.child = child def __getattr__(self, attr): print("Calling __getattr__: "+attr) if hasattr(self.ch

概述

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)

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

但是调用person.make_statement(20)的参数怎么通过__getattr__?我可以在__getattr__函数中打印出数字“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

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

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

总结

以上是编程之家为你收集整理的python – 参数如何通过__getattr__传递给一个函数全部内容,希望文章能够帮你解决python – 参数如何通过__getattr__传递给一个函数所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶