Python的getattr用法

getattr()函数是Python自省的核心函数,具体使用大体如下:

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


举例代码如下:

# -*- coding:utf-8 -*-
class Test(object):
    a = 10

    def __init__(self):
        pass

    def test_getattr(self):
        b = 20
        return b

if __name__ == '__main__':
    t = Test()

    # 获取对象 t 中的test_getattr方法
    result_1 = getattr(t, 'test_getattr', 'NO_Method')
    # 获取对象 t 中的 a 变量,如果没有。使用default
    result_2 = getattr(t, 'a', 'default')
    # 获取对象 t 中的 c 变量,如果没有。使用default
    result_3 = getattr(t, 'c', 'default')
    # 获取对象 t 中的test_getattr方法,并执行
    result_4 = getattr(t, 'test_getattr')()

    print 'result_1 =', result_1
    print 'result_2 =', result_2
    print 'result_3 =', result_3
    print 'result_4 =', result_4
输出结果:

result_1 = <bound method Test.test_getattr of <__main__.Test object at 0x029FB230>>
result_2 = 10
result_3 = default
result_4 = 20



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值