Python的getattr() 使用方法 简单版
来源:互联网 发布:ios判断网络连接状态 编辑:程序博客网 时间:2024/05/01 05:41
getattr()函数是Python自省的核心函数,具体使用大体如下:
10.1.5
Getattr用于返回一个对象属性,或者方法
Python代码
- class
A: -
def __init__(self): -
self.a = 'a' -
def method(self): -
print "method print" -
- a = A()
- print
getattr(a, 'a', 'default') #如果有属性a则打印a,否则打印default - print
getattr(a, 'b', 'default') #如果有属性b则打印b,否则打印default - print
getattr(a, 'method', 'default') - #如果有方法method,否则打印其地址,否则打印default
- print
getattr(a, 'method', 'default')() - #如果有方法method,运行函数并打印None否则打印default
注:使用getattr可以轻松实现工厂模式。
例:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出
Python代码
- import
statsout - def
output(data, format="text"): -
output_function = getattr(statsout, "output_%s" % format) -
return output_function(data)
0 0
- Python的getattr() 使用方法 简单版
- Python的hasattr() getattr() setattr() 函数使用方法
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的getattr函数
- Linux操作系统学习笔记之linux基本命令
- 银行卡三元素实名认证
- Hdu 5510 Bazinga(KMP+尺取法)
- 全局变量可不可以定义在可被多个.c文件包含的头文件中
- mybatis通用mapper的使用
- Python的getattr() 使用方法 简单版
- Android NDK JNI 入门
- mysql字典库部分字段说明(一)之 STATISTICS索引
- ScrollView使用总结
- sublime text 3 在写 css 时自动提示类名的解决方案
- oracle 12c查询数据库名、实例名等
- 大型网站架构之分布式消息队列
- MySql 局部-全局临时表 temporary表是session级的,创建后用show tables也看不到它。
- centos下svn的搭建