您的位置:首页 > 编程语言 > Python开发

Python的getattr用法

2016-07-08 17:09 441 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python getattr