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 16 Python
Python虚拟环境virtualenv的安装与使用详解
May 28 Python
Django与JS交互的示例代码
Aug 23 Python
Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能示例
Aug 31 Python
使用python为mysql实现restful接口
Jan 05 Python
python生成n个元素的全组合方法
Nov 13 Python
python如何实现从视频中提取每秒图片
Oct 22 Python
python实现屏保程序(适用于背单词)
Jul 30 Python
使用python处理题库表格并转化为word形式的实现
Apr 14 Python
python使用bs4爬取boss直聘静态页面
Oct 10 Python
学会迭代器设计模式,帮你大幅提升python性能
Jan 03 Python
Python代码,能玩30多款童年游戏!这些有几个是你玩过的
Apr 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
PHP register_shutdown_function()函数的使用示例
2015/06/23 PHP
PHP4和PHP5版本下解析XML文档的操作方法实例分析
2017/05/20 PHP
浅谈PHP中pack、unpack的详细用法
2018/03/12 PHP
jquery tools 系列 scrollable(2)
2009/09/06 Javascript
与jquery serializeArray()一起使用的函数,主要来方便提交表单
2011/01/31 Javascript
Javascript 类、命名空间、代码组织代码
2011/07/31 Javascript
人人网javascript面试题 可以提前实现下
2012/01/05 Javascript
js控制href内容的连接内容的变化示例
2014/04/30 Javascript
js代码实现点击按钮出现60秒倒计时
2021/01/28 Javascript
jquery中实现时间戳与日期相互转换
2016/04/12 Javascript
JS基于clipBoard.js插件实现剪切、复制、粘贴
2016/05/03 Javascript
JavaScript用构造函数如何获取变量的类型名
2016/12/23 Javascript
node.js中EJS 模板快速入门教程
2017/05/08 Javascript
Angular+Bootstrap+Spring Boot实现分页功能实例代码
2017/07/21 Javascript
一个简易的js图片轮播效果
2017/07/22 Javascript
Mac 安装 nodejs方法(图文详细步骤)
2017/10/30 NodeJs
在vue使用clipboard.js进行一键复制文本的实现示例
2019/01/15 Javascript
js实现从右往左匀速显示图片(无缝轮播)
2020/06/29 Javascript
vue+Element-ui实现分页效果
2020/11/15 Javascript
python抓取网页内容示例分享
2014/02/24 Python
python实现批量图片格式转换
2020/06/16 Python
Python实现的tcp端口检测操作示例
2018/07/24 Python
带你认识Django
2019/01/15 Python
python能做什么 python的含义
2019/10/12 Python
django处理select下拉表单实例(从model到前端到post到form)
2020/03/13 Python
详解Python中string模块除去Str还剩下什么
2020/11/30 Python
澳大利亚墨水站Ink Station:墨水和碳粉打印机墨盒
2019/03/24 全球购物
出口公司经理求职简历中的自我评价
2013/10/13 职场文书
函授生自我鉴定
2014/03/25 职场文书
2014年创先争优活动总结
2014/05/04 职场文书
国庆节促销广告语2014
2014/09/19 职场文书
教师工作表现评语
2014/12/31 职场文书
2015年护士节慰问信
2015/03/23 职场文书
干部培训简讯
2015/07/20 职场文书
使用 Apache 反向代理的设置技巧
2022/01/18 Servers
python创建字典及相关管理操作
2022/04/13 Python