python – 参数如何通过__getattr__传递给一个函数
发布时间:2020-12-30 14:26:11 所属栏目: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
|
考虑下面的代码示例( 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)
可以显示,函数调用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打印: >>> 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 – 列表中的命名元组
- python – 是否有任何方法可以使用openpyxl获取.xlsx表中存
- python – SQLAlchemy过滤器查询由相关对象
- python – 如果列超过特定数量的NA值,则删除该列
- python – 在大熊猫中合并多索引的单索引数据帧
- python – 如何为Xerox打印机创建动态作业单?
- python – 将NumPy对象与“None”进行比较时的FutureWarnin
- python – 从scipy.stats … rvs和numpy.random的随机抽取之
- python – ElementTree find()/ findall()找不到带命名空间
- TypeError:’function’对象不可订阅 – Python
推荐文章
站长推荐
- python – 如何使用多个服务器进行Flask登录
- python – Flask:如何在蓝图中的每个路径之前运
- python – 整数除法:对于所有整数a,b,// b == i
- 如何规范化python中的字符串列表?
- `with canvas:`(Python`with something()as x:
- version-control – 更改Mercurial中的目录结构
- 使用python,自动确定用户当前时区的最准确方法是
- python – Pandas:根据来自另一列的匹配替换列值
- python-2.7 – 在Python 2.7中手动构建ConfigPar
- python – 如何将二进制转换为浮点数
热点阅读
