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递归遍历列表及输出的实现方法
May 19 Python
Python实现发送QQ邮件的封装
Jul 14 Python
使用Python的turtle模块画图的方法
Nov 15 Python
django的登录注册系统的示例代码
May 14 Python
Python自定义一个类实现字典dict功能的方法
Jan 19 Python
python 模拟贷款卡号生成规则过程解析
Aug 30 Python
Django中间件拦截未登录url实例详解
Sep 03 Python
python下载库的步骤方法
Oct 12 Python
python 中Arduino串口传输数据到电脑并保存至excel表格
Oct 14 Python
Python轻量级web框架bottle使用方法解析
Jun 13 Python
python中time.ctime()实例用法
Feb 03 Python
Python Django / Flask如何使用Elasticsearch
Apr 19 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
PHP中的string类型使用说明
2010/07/27 PHP
PHP 强制下载文件代码
2010/10/24 PHP
php中inlcude()性能对比详解
2012/09/16 PHP
PHP 面向对象程序设计(oop)学习笔记 (五) - PHP 命名空间
2014/06/12 PHP
PHP多个文件上传到服务器实例
2014/10/29 PHP
PHP上传文件及图片到七牛的方法
2018/07/25 PHP
Javascript Boolean、Nnumber、String 强制类型转换的区别详细介绍
2012/12/13 Javascript
JS、CSS加载中的小问题探讨
2013/11/26 Javascript
jquery修改属性值实例代码(设置属性值)
2014/01/06 Javascript
jquery实现select选中行、列合计示例
2014/04/25 Javascript
javascript实现点击商品列表checkbox实时统计金额的方法
2015/05/15 Javascript
js防阻塞加载的实现方法
2016/09/09 Javascript
AngularJS监听ng-repeat渲染完成的方法
2018/03/20 Javascript
jQuery中ajax请求后台返回json数据并渲染HTML的方法
2018/08/08 jQuery
python获取元素在数组中索引号的方法
2015/07/15 Python
横向对比分析Python解析XML的四种方式
2016/03/30 Python
Python中列表元素转为数字的方法分析
2016/06/14 Python
python3.6连接MySQL和表的创建与删除实例代码
2017/12/28 Python
python装饰器常见使用方法分析
2019/06/26 Python
Python学习笔记之For循环用法详解
2019/08/14 Python
Django上线部署之IIS的配置方法
2019/08/22 Python
在python中使用pymysql往mysql数据库中插入(insert)数据实例
2020/03/02 Python
基于python实现对文件进行切分行
2020/04/26 Python
python如何变换环境
2020/07/21 Python
CSS3网格的三个新特性详解
2014/04/04 HTML / CSS
世界上最大的糖果店:Dylan’s Candy Bar
2017/11/07 全球购物
英国排名第一的停车场运营商:NCP
2019/08/26 全球购物
俄罗斯三星品牌商店:GalaxyStore
2020/11/04 全球购物
大一新生学期自我评价
2014/04/09 职场文书
党员承诺书怎么写
2014/05/20 职场文书
2014年端午节演讲稿范文
2014/05/23 职场文书
贫困证明模板(3篇)
2014/09/16 职场文书
2014年党的群众路线活动个人整改措施
2014/10/28 职场文书
走进毛泽东观后感
2015/06/04 职场文书
2016春季运动会开幕词
2016/03/04 职场文书
css3新特性的应用示例分析
2022/03/16 HTML / CSS