python中getattr函数使用方法 getattr实现工厂模式


Posted in Python onJanuary 20, 2014

看了下函数本身的doc

getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. 
When a default argument is given, it is returned when the attribute doesn't 
exist; without it, an exception is raised in that case.

解释的很抽象 告诉我这个函数的作用相当于是

object.name

试了一下getattr(object,name)确实和object.name是一样的功能.只不过这里可以把name作为一个变量去处理书上的例子很好的说明了这个函数的功用,使用getattr可以轻松实现工厂模式。

例:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出

import statsout 
def output(data, format="text"):                           
    output_function = getattr(statsout, "output_%s" %format) 
    return output_function(data)
[code]
这个例子中可以根据传入output函数的format参数的不同 去调用statsout模块不同的方法(用格式化字符串实现output_%s)
返回的是这个方法的对象 就可以直接使用了 如果要添加新的格式 只需要在模块中写入新的方法函数 在调用output函数时使用新的参数就可以使用不同的格式输出
确实很方便

为了加深对getattr函数的理解 转载一篇英文的说明
Python's getattr function is used to fetch an attribute from an object, using a string object instead of an identifier to identify the attribute. In other words, the following two statements are equivalent:
[code]
value = obj.attribute
value = getattr(obj, "attribute")
If the attribute exists, the corresponding value is returned. If the attribute does not exist, you get an AttributeError exception instead.
The getattr function can be used on any object that supports dotted notation (by implementing the __getattr__ method). This includes class objects, modules, and even function objects.
path = getattr(sys, "path")
doc = getattr(len, "__doc__")
The getattr function uses the same lookup rules as ordinary attribute access, and you can use it both with ordinary attributes and methods:
result = obj.method(args)
func = getattr(obj, "method")
result = func(args)
or, in one line:
result = getattr(obj, "method")(args)
Calling both getattr and the method on the same line can make it hard to handle exceptions properly. To avoid confusing AttributeError exceptions raised by getattr with similar exceptions raised inside the method, you can use the following pattern:
try:
    func = getattr(obj, "method")
except AttributeError:
    ... deal with missing method ...
else:
    result = func(args)
The function takes an optional default value, which is used if the attribute doesn't exist. The following example only calls the method if it exists:
func = getattr(obj, "method", None)
if func:
    func(args)
Here's a variation, which checks that the attribute is indeed a callable object before calling it.
func = getattr(obj, "method", None)
if callable(func):
    func(args)
Python 相关文章推荐
python在windows命令行下输出彩色文字的方法
Mar 19 Python
详解Python中的文件操作
Aug 28 Python
更改Ubuntu默认python版本的两种方法python-> Anaconda
Dec 18 Python
浅谈numpy数组的几种排序方式
Dec 15 Python
Django 实现下载文件功能的示例
Mar 06 Python
Python 查看list中是否含有某元素的方法
Jun 27 Python
Python设计模式之备忘录模式原理与用法详解
Jan 15 Python
使用Python完成15位18位身份证的互转功能
Nov 06 Python
Python中求对数方法总结
Mar 10 Python
Python celery原理及运行流程解析
Jun 13 Python
Numpy 多维数据数组的实现
Jun 18 Python
梳理总结Python开发中需要摒弃的18个坏习惯
Jan 22 Python
python字符串加密解密的三种方法分享(base64 win32com)
Jan 19 #Python
python实现人人网登录示例分享
Jan 19 #Python
使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例
Jan 19 #Python
压缩包密码破解示例分享(类似典破解)
Jan 17 #Python
vc6编写python扩展的方法分享
Jan 17 #Python
python的urllib模块显示下载进度示例
Jan 17 #Python
Python中for循环详解
Jan 17 #Python
You might like
实现分十页分向前十页向后十页的处理
2006/10/09 PHP
PHP脚本的10个技巧(5)
2006/10/09 PHP
smarty模板嵌套之include与fetch性能测试
2010/12/05 PHP
Yii查询生成器(Query Builder)用法实例教程
2014/09/04 PHP
Windows下的PHP 5.3.x安装 Zend Guard Loader教程
2014/09/06 PHP
详解WordPress中提醒安装插件以及隐藏插件的功能实现
2015/12/25 PHP
Google Suggest ;-) 基于js的动态下拉菜单
2006/10/11 Javascript
Cookie 注入是怎样产生的
2009/04/08 Javascript
prototype 中文参数乱码解决方案
2009/11/09 Javascript
Jquery UI震动效果实现原理及步骤
2013/02/04 Javascript
JS中setTimeout()的用法详解
2013/04/14 Javascript
在子窗口中关闭父窗口的一句代码
2013/10/21 Javascript
下拉框select的绑定示例
2014/09/04 Javascript
基于javascript实现图片预加载
2016/01/05 Javascript
JavaScript预解析及相关技巧分析
2016/04/21 Javascript
简单分析javascript中的函数
2016/09/10 Javascript
jQuery实现带遮罩层效果的blockUI弹出层示例【附demo源码下载】
2016/09/14 Javascript
有趣的bootstrap走动进度条
2016/12/01 Javascript
jquery实时获取时间的简单实例
2017/01/26 Javascript
高效的jQuery代码编写技巧总结
2017/02/22 Javascript
JS实现将对象转化为数组的方法分析
2019/01/21 Javascript
TypeScript类型声明书写详解
2019/08/28 Javascript
Element Alert警告的具体使用方法
2020/07/27 Javascript
python赋值操作方法分享
2013/03/23 Python
用Python实现服务器中只重载被修改的进程的方法
2015/04/30 Python
python中利用Future对象回调别的函数示例代码
2017/09/07 Python
在NumPy中创建空数组/矩阵的方法
2018/06/15 Python
Flask Web开发入门之文件上传(八)
2018/08/17 Python
对Python3 goto 语句的使用方法详解
2019/02/16 Python
Python多线程爬取豆瓣影评API接口
2019/10/22 Python
pycharm 设置项目的根目录教程
2020/02/12 Python
自学python用什么系统好
2020/06/23 Python
美国领先的家庭健康检测试剂盒提供商:LetsGetChecked
2019/03/18 全球购物
2015年七一建党节活动总结
2015/03/20 职场文书
解决Python字典查找报Keyerror的问题
2021/05/26 Python
Go语言并发编程 sync.Once
2021/10/16 Golang