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实现抓取网页并且解析的实例
Sep 20 Python
Python简单调用MySQL存储过程并获得返回值的方法
Jul 20 Python
21行Python代码实现拼写检查器
Jan 25 Python
Python 爬虫的工具列表大全
Jan 31 Python
Python+Opencv识别两张相似图片
Mar 23 Python
python中的字典使用分享
Jul 31 Python
python利用不到一百行代码实现一个小siri
Mar 02 Python
Python爬虫之网页图片抓取的方法
Jul 16 Python
Pycharm保存不能自动同步到远程服务器的解决方法
Jun 27 Python
GDAL 矢量属性数据修改方式(python)
Mar 10 Python
深入浅析python 中的self和cls的区别
Jun 20 Python
Opencv常见图像格式Data Type及代码实例
Nov 02 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
日本十大科幻动漫 宇宙骑士垫底,第一已成经典
2020/03/04 日漫
PHP简单实现无限级分类的方法
2016/05/13 PHP
php 伪造HTTP_REFERER页面URL来源的三种方法
2016/09/22 PHP
在laravel5.2中实现点击用户头像更改头像的方法
2019/10/14 PHP
JQuery 绑定select标签的onchange事件,弹出选择的值,并实现跳转、传参
2011/01/06 Javascript
jQuery中clearQueue()方法用法实例
2014/12/29 Javascript
js封装可使用的构造函数继承用法分析
2015/01/28 Javascript
PHP+jQuery+Ajax实现多图片上传效果
2015/03/14 Javascript
chrome不支持form.submit的解决方案
2015/04/28 Javascript
浅谈document.write()输出样式
2015/05/07 Javascript
JS实现自定义简单网页软键盘效果代码
2015/11/05 Javascript
基于JS实现textarea中获取动态剩余字数的方法
2016/05/25 Javascript
详解Angular2表单-模板驱动的表单(Template-Driven Forms)
2017/08/04 Javascript
详解react使用react-bootstrap当轮子造车
2017/08/15 Javascript
javascript将json格式数组下载为excel表格的方法
2017/12/22 Javascript
webpack+vue.js构建前端工程化的详细教程
2020/05/10 Javascript
ES6 Generator基本使用方法示例
2020/06/06 Javascript
JS异步宏队列与微队列原理区别详解
2020/07/02 Javascript
python使用calendar输出指定年份全年日历的方法
2015/04/04 Python
Python selenium 三种等待方式解读
2016/09/15 Python
python获取外网IP并发邮件的实现方法
2017/10/01 Python
python中is与双等于号“==”的区别示例详解
2017/11/21 Python
儿童学习python的一些小技巧
2018/05/27 Python
python3去掉string中的标点符号方法
2019/01/22 Python
详解Python计算机视觉 图像扭曲(仿射扭曲)
2019/03/27 Python
Python3中_(下划线)和__(双下划线)的用途和区别
2019/04/26 Python
Python实现语音识别和语音合成功能
2019/09/20 Python
Hashtable 添加内容的方式有哪几种,有什么区别?
2012/04/08 面试题
Java基础知识面试题
2014/03/25 面试题
双语教学实施方案
2014/03/23 职场文书
政治思想表现评语
2014/05/04 职场文书
会计专业自荐书
2014/07/08 职场文书
2014年大学生党员自我评议
2014/09/22 职场文书
党的群众路线对照检查材料范文
2014/09/24 职场文书
只需要12页,掌握撰写一流商业计划书的技巧
2019/05/07 职场文书
导游词之青城山景区
2019/09/27 职场文书