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下如何让web元素的生成更简单的分析
Jul 17 Python
详解django三种文件下载方式
Apr 06 Python
pandas DataFrame 删除重复的行的实现方法
Jan 29 Python
scrapy-redis的安装部署步骤讲解
Feb 27 Python
Django 使用easy_thumbnails压缩上传的图片方法
Jul 26 Python
Python检查图片是否损坏及图片类型是否正确过程详解
Sep 30 Python
Python TKinter如何自动关闭主窗口
Feb 26 Python
浅谈opencv自动光学检测、目标分割和检测(连通区域和findContours)
Jun 04 Python
Keras之自定义损失(loss)函数用法说明
Jun 10 Python
Python使用正则表达式实现爬虫数据抽取
Aug 17 Python
python中温度单位转换的实例方法
Dec 27 Python
Python使用psutil库对系统数据进行采集监控的方法
Aug 23 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遍历数组的方法汇总
2015/04/30 PHP
PHP购物车类Cart.class.php定义与用法示例
2016/07/20 PHP
PHP排序算法之堆排序(Heap Sort)实例详解
2018/04/21 PHP
实现php删除链表中重复的结点
2018/09/27 PHP
EXTJS FORM HIDDEN TEXTFIELD 赋值 使用value不好用的问题
2011/04/16 Javascript
用nodejs写的一个简单项目打包工具
2013/05/11 NodeJs
jquery给图片添加鼠标经过时的边框效果
2013/11/12 Javascript
input:checkbox多选框实现单选效果跟radio一样
2014/06/16 Javascript
js+div实现文字滚动和图片切换效果代码
2015/08/27 Javascript
Js制作点击输入框时默认文字消失的效果
2015/09/05 Javascript
JS实现带鼠标效果的头像及文章列表代码
2015/09/27 Javascript
js clearInterval()方法的定义和用法
2015/11/11 Javascript
jQuery旋转木马式幻灯片轮播特效
2015/12/04 Javascript
jQuery弹出div层过2秒自动消失
2016/11/29 Javascript
详解javascript获取url信息的常见方法
2016/12/19 Javascript
基于jQuery实现顶部导航栏功能
2016/12/27 Javascript
mongoose中利用populate处理嵌套的方法
2017/05/26 Javascript
深入理解vue Render函数
2017/07/19 Javascript
在JavaScript中如何访问暂未存在的嵌套对象
2019/06/18 Javascript
详解NodeJs项目 CentOs linux服务器线上部署
2019/09/16 NodeJs
Vue3 中的数据侦测的实现
2019/10/09 Javascript
Ant Design Vue table中列超长显示...并加提示语的实例
2020/10/31 Javascript
Python字符遍历的艺术
2008/09/06 Python
Python实现的简单模板引擎功能示例
2017/09/02 Python
如何安装多版本python python2和python3共存以及pip共存
2018/09/18 Python
在Python中将函数作为另一个函数的参数传入并调用的方法
2019/01/22 Python
解决python flask中config配置管理的问题
2019/07/26 Python
python retrying模块的使用方法详解
2019/09/25 Python
女性时尚网购:Chic Me
2019/07/30 全球购物
俄罗斯购买内衣网站:Trusiki
2020/08/22 全球购物
IMPORT的选项IGNORE有什么作用?缺省是什么设置?
2015/09/17 面试题
倡导文明标语
2014/06/16 职场文书
民政局副局长民主生活会个人对照检查材料
2014/09/19 职场文书
党员干部四风问题整改措施思想汇报
2014/10/12 职场文书
2015元旦标语横幅
2014/12/09 职场文书
2015年暑假生活总结
2015/07/13 职场文书