您现在的位置是:首页 > 文章详情

Python自省函数getattr的用法

日期:2018-07-18点击:265

首先把官方文档搬出来:


img_9454e7ccbc62445ddc1934f0e9d42f50.png
doc.png

英文棒的小伙伴们最好是去看下官方文档,毕竟原汁原味的英文表述才最准确。
Python3.6 getattr 官方文档

getattr()函数是Python自省的核心函数,可以把一个要访问的变量或方法,通过字符串的形式传递过去并拿到返回的值。

获取对象引用getattr
getattr用于返回一个对象属性,或者方法

示例代码:

class Demo: def __init__(self): self.name = 'allen' self.age = '18' def method_one(self): print("这是 method_one 方法") return "one" def method_two(self): print("这是 method_two 方法") d = Demo() # 如果d对象中有属性name则打印self.name的值,否则打印'not find' print(getattr(d, 'name', 'not found')) # 如果d对象中有属性name则打印self.age的值,否则打印'not find' print(getattr(d, 'age', 'not found')) # 如果有方法method_one,打印其地址,否则打印default print(getattr(d, 'method_one', 'default')) # 如果有方法method_one,运行函数并打印返回值,否则,打印default print(getattr(d, 'method_one', 'default')()) # 如果有方法method,运行函数并打印None否则打印default print(getattr(d, 'method_two', 'default')()) 

解释一下上图的示例代码:
定义一个Demo类,有两个变量nameage,还有两个方法method_onemethod_two
method_one方法打印一句话并返回one这个字符串;
method_two方法打印一句话没有任何返回值;


print(getattr(d, 'name', 'not found')):
获取d对象的name属性,如果name属性没有,返回not found。
运行结果:allen


print(getattr(d, 'age', 'not found')):
获取d对象的age属性,如果age属性没有,返回not found。
运行结果:not found


print(getattr(d, 'method_one', 'default')):
获取d对象的method_one方法的地址,如果method_one方法没有,返回default。
运行结果:<bound method Demo.method_one of <__main__.Demo object at 0x10cbcb9e8>>


print(print(getattr(d, 'method_one', 'default')()):
获取d对象的method_one方法并运行,且打印返回值。如果method_one方法没有,返回default。
运行结果:
这是 method_one 方法
one


print(getattr(d, 'method_two', 'default')()):
获取d对象的method_two方法并运行,且打印返回值。如果method_two方法没有,返回default。
运行结果:
这是 method_one 方法
None


原文链接:https://yq.aliyun.com/articles/654555
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章