Python自省函数getattr的用法

首先把官方文档搬出来:


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值