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动态加载变量示例分享
Feb 17 Python
Python实现的一个简单LRU cache
Sep 26 Python
利用Python的装饰器解决Bottle框架中用户验证问题
Apr 24 Python
将Django框架和遗留的Web应用集成的方法
Jul 24 Python
利用python发送和接收邮件
Sep 27 Python
Python错误: SyntaxError: Non-ASCII character解决办法
Jun 08 Python
Python中GIL的使用详解
Oct 03 Python
Python实现FM算法解析
Jun 18 Python
详解Python对JSON中的特殊类型进行Encoder
Jul 15 Python
Python协程 yield与协程greenlet简单用法示例
Nov 22 Python
flask的orm框架SQLAlchemy查询实现解析
Dec 12 Python
python 动态绘制爱心的示例
Sep 27 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
FirePHP 推荐一款PHP调试工具
2011/04/23 PHP
php调用mysql存储过程实例分析
2014/12/29 PHP
在CentOS上搭建LAMP+vsftpd环境的简单指南
2015/08/01 PHP
phpcms的分类名称和类别名称的调用
2017/01/05 PHP
微信第三方登录(原生)demo【必看篇】
2017/05/26 PHP
关于php unset对json_encode的影响详解
2018/11/14 PHP
js取滚动条的尺寸的函数代码
2011/11/30 Javascript
javascript dom追加内容实现示例
2013/09/21 Javascript
通过onmouseover选项卡实现img图片的变化
2014/02/12 Javascript
javascript中的3种继承实现方法
2016/01/27 Javascript
JQuery解析XML的方法小结
2016/04/02 Javascript
bootstrap网页框架的使用方法
2016/05/10 Javascript
js跨域资源共享 基础篇
2016/07/02 Javascript
Bootstrap导航条的使用和理解3
2016/12/14 Javascript
jQuery无冲突模式详解
2019/01/17 jQuery
微信小程序的mpvue框架快速上手指南
2019/05/15 Javascript
Vue.js组件实现选项卡以及切换特效
2019/07/24 Javascript
原生js+ajax分页组件
2020/01/30 Javascript
js面试题之异步问题的深入理解
2020/09/20 Javascript
python使用sorted函数对列表进行排序的方法
2015/04/04 Python
Python装饰器的执行过程实例分析
2018/06/04 Python
Windows下Anaconda2安装NLTK教程
2018/09/19 Python
python打开windows应用程序的实例
2019/06/28 Python
Python 为什么推荐蛇形命名法原因浅析
2020/06/18 Python
python wsgiref源码解析
2021/02/06 Python
技术学校毕业生求职信分享
2013/12/02 职场文书
会计学专业学生的求职信范文
2014/01/27 职场文书
学习雷锋精神心得体会范文
2014/03/12 职场文书
产品生产计划书
2014/05/07 职场文书
社区先进事迹材料
2014/05/19 职场文书
2014年群众路线党员自我评议
2014/09/24 职场文书
优秀护士事迹材料
2014/12/25 职场文书
个人先进事迹总结
2015/02/26 职场文书
预备党员自我评价范文
2015/03/04 职场文书
酒店厨房管理制度
2015/08/06 职场文书
Spring事务管理下synchronized锁失效问题的解决方法
2022/03/31 Java/Android