getattr()函数是Python自省的核心函数,具体使用大体如下:
10.1.5
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