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
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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法