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 05 Python
Python调用微信公众平台接口操作示例
Jul 08 Python
关于python pyqt5安装失败问题的解决方法
Aug 08 Python
Python中django学习心得
Dec 06 Python
python 使用 requests 模块发送http请求 的方法
Dec 09 Python
Python 中Django验证码功能的实现代码
Jun 20 Python
解决在pycharm运行代码,调用CMD窗口的命令运行显示乱码问题
Aug 23 Python
在jupyter notebook中调用.ipynb文件方式
Apr 14 Python
Python3爬虫中Ajax的用法
Jul 10 Python
Python脚本实现Zabbix多行日志监控过程解析
Aug 26 Python
Python远程linux执行命令实现
Nov 11 Python
如何利用opencv判断两张图片是否相同详解
Jul 07 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
高分R级DC动画剧《哈莉·奎茵》第二季正式预告首发
2020/04/09 欧美动漫
PHP Global变量定义当前页面的全局变量实现探讨
2013/06/05 PHP
浅析php设计模式之数据对象映射模式
2016/03/03 PHP
Thinkphp通过一个入口文件如何区分移动端和PC端
2017/04/18 PHP
tp5修改(实现即点即改)
2019/10/18 PHP
Nigma vs Alliance BO5 第五场2.14
2021/03/10 DOTA
jquery checkbox全选、取消全选实现代码
2010/03/05 Javascript
jquery 与NVelocity 产生冲突的解决方法
2011/06/13 Javascript
解决jquery异步按一定的时间间隔刷新问题
2012/12/10 Javascript
jquery实现固定顶部导航效果(仿蘑菇街)
2013/03/21 Javascript
js取消单选按钮选中示例代码
2013/11/14 Javascript
node中socket.io的事件使用详解
2014/12/15 Javascript
jquery判断至少有一个checkbox被选中的方法
2015/06/05 Javascript
如何用angularjs制作一个完整的表格
2016/01/21 Javascript
原生JS实现图片左右轮播
2016/12/30 Javascript
BootStrap 获得轮播中的索引和当前活动的焦点对象
2017/05/11 Javascript
vue-cli + sass 的正确打开方式图文详解
2017/10/27 Javascript
微信小程序模板和模块化用法实例分析
2017/11/28 Javascript
图文介绍Vue父组件向子组件传值
2018/02/17 Javascript
Vue数据监听方法watch的使用
2018/03/28 Javascript
jquery.onoff实现简单的开关按钮功能(推荐)
2018/05/24 jQuery
微信小程序扫描二维码获取信息实例详解
2019/05/07 Javascript
python实现倒计时的示例
2014/02/14 Python
使用Python的Scrapy框架编写web爬虫的简单示例
2015/04/17 Python
python解析xml文件实例分析
2015/05/27 Python
python 实现批量xls文件转csv文件的方法
2018/10/23 Python
Numpy截取指定范围内的数据方法
2018/11/14 Python
使用 Python 遍历目录树的方法
2020/02/29 Python
台湾母婴用品购物网站:Infant婴之房
2018/06/15 全球购物
linux面试题参考答案(4)
2014/09/21 面试题
三个Unix的命令面试题
2015/04/12 面试题
春风行动实施方案
2014/03/28 职场文书
机关保密承诺书
2014/06/03 职场文书
《玩出了名堂》教学反思
2016/02/17 职场文书
世界十大狙击步枪排行榜
2022/03/20 杂记
利用 Python 的 Pandas和 NumPy 库来清理数据
2022/04/13 Python