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 08 Python
python的文件操作方法汇总
Nov 10 Python
python2 与 pyhton3的输入语句写法小结
Sep 10 Python
Python 中的lambda函数介绍
Oct 10 Python
对Xpath 获取子标签下所有文本的方法详解
Jan 02 Python
python单线程文件传输的实例(C/S)
Feb 13 Python
Python中如何使用if语句处理列表实例代码
Feb 24 Python
在python中实现调用可执行文件.exe的3种方法
Jul 07 Python
Python绘制堆叠柱状图的实例
Jul 09 Python
在python3.64中安装pyinstaller库的方法步骤
Jun 02 Python
django 获取字段最大值,最新的记录操作
Aug 09 Python
如何利用python创作字符画
Jun 25 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常用开发函数解析之数组篇[未完结]
2012/07/30 PHP
php接口和抽象类使用示例详解
2014/03/02 PHP
一个经典的PHP文件上传类分享
2014/11/18 PHP
浅谈PHP各环境下的伪静态配置
2019/03/13 PHP
JavaScript 学习笔记(五)
2009/12/31 Javascript
jquery中的常用事件bind、hover、toggle等示例介绍
2014/07/21 Javascript
jQuery实现跟随鼠标运动图层效果的方法
2015/02/02 Javascript
jQuery+HTML5+CSS3制作支持响应式布局时间轴插件
2016/08/10 Javascript
Js查找字符串中出现次数最多的字符及个数实例解析
2016/09/05 Javascript
js判断价格,必须为数字且不能为负数的实现方法
2016/10/07 Javascript
Bootstrap轮播插件使用代码
2016/10/11 Javascript
Three.js加载外部模型的教程详解
2017/11/10 Javascript
使用vux实现上拉刷新功能遇到的坑
2018/02/08 Javascript
基于vue 添加axios组件,解决post传参数为null的问题
2018/03/05 Javascript
解决vue接口数据赋值给data没有反应的问题
2018/08/27 Javascript
详解微信小程序开发用户授权登陆
2019/04/24 Javascript
layui table设置某一行的字体颜色方法
2019/09/05 Javascript
vue监听用户输入和点击功能
2019/09/27 Javascript
javascript异常处理实现原理详解
2020/02/17 Javascript
JavaScript实现PC端四格密码输入框功能
2020/02/19 Javascript
JavaScript 空间坐标的使用
2020/08/19 Javascript
[10:14]2018DOTA2国际邀请赛寻真——paiN Gaming不仅为自己而战
2018/08/14 DOTA
python制作花瓣网美女图片爬虫
2015/10/28 Python
python UNIX_TIMESTAMP时间处理方法分析
2016/04/18 Python
深入理解python中的select模块
2017/04/23 Python
Python入门之三角函数tan()函数实例详解
2017/11/08 Python
python实现简单登陆流程的方法
2018/04/22 Python
python+opencv实现霍夫变换检测直线
2020/10/23 Python
Django框架之中间件MiddleWare的实现
2019/12/30 Python
StubHub新西兰:购买和出售你的门票
2019/04/22 全球购物
新学期国旗下演讲稿
2014/05/08 职场文书
小学感恩教育活动总结
2014/07/07 职场文书
社区党建工作汇报材料
2014/08/14 职场文书
写给汽车4S店的创业计划书,拿来即用!
2019/08/09 职场文书
CSS3 实现的图片悬停的切换按钮
2021/04/13 HTML / CSS
利用Apache Common将java对象池化的问题
2022/06/16 Servers