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数据结构之图深度优先和广度优先实例详解
Jul 08 Python
Python实现配置文件备份的方法
Jul 30 Python
python http接口自动化脚本详解
Jan 02 Python
Python实现拷贝/删除文件夹的方法详解
Aug 29 Python
scrapy-redis的安装部署步骤讲解
Feb 27 Python
python实现视频分帧效果
May 31 Python
pytz格式化北京时间多出6分钟问题的解决方法
Jun 21 Python
Django之模板层的实现代码
Sep 09 Python
解决jupyter notebook显示不全出现框框或者乱码问题
Apr 09 Python
django model 条件过滤 queryset.filter(**condtions)用法详解
May 20 Python
django下创建多个app并设置urls方法
Aug 02 Python
Django项目在pycharm新建的步骤方法
Mar 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
给php新手谈谈我的学习心得
2007/02/25 PHP
PHP性能优化准备篇图解PEAR安装
2011/12/05 PHP
浅谈使用 PHP 进行手机 APP 开发(API 接口开发)
2014/08/11 PHP
深入解析PHP中SESSION反序列化机制
2017/03/01 PHP
PHP实现的简单留言板功能示例【基于thinkPHP框架】
2018/12/07 PHP
PHP面向对象程序设计中的self、static、parent关键字用法分析
2019/08/14 PHP
wordpress之js库集合研究介绍
2007/08/17 Javascript
javascript写的日历类(基于pj)
2010/12/28 Javascript
详解基于webpack搭建react运行环境
2017/06/01 Javascript
vue.js使用watch监听路由变化的方法
2018/07/08 Javascript
vue实现编辑器键盘抬起时内容跟随光标距顶位置向上滚动效果
2020/05/28 Javascript
Vue中component标签解决项目组件化操作
2020/09/04 Javascript
Flexible.js可伸缩布局实现方法详解
2020/11/13 Javascript
[06:01]刀塔次级联赛top10第一期
2014/11/07 DOTA
Python中zip()函数用法实例教程
2014/07/31 Python
详解Python的Django框架中的模版继承
2015/07/16 Python
基于Python如何使用AIML搭建聊天机器人
2016/01/27 Python
Python连接mysql数据库的正确姿势
2016/02/03 Python
Python3安装Scrapy的方法步骤
2017/11/23 Python
解决pycharm界面不能显示中文的问题
2018/05/23 Python
Python爬虫包BeautifulSoup学习实例(五)
2018/06/17 Python
python 读取文本文件的行数据,文件.splitlines()的方法
2018/07/12 Python
opencv3/python 鼠标响应操作详解
2019/12/11 Python
关于TensorFlow新旧版本函数接口变化详解
2020/02/10 Python
python GUI库图形界面开发之PyQt5动态加载QSS样式文件
2020/02/25 Python
CSS实现鼠标滑过鼠标点击代码写法
2016/12/26 HTML / CSS
HTML5 Canvas draw方法制作动画效果示例
2013/07/11 HTML / CSS
韩国爱茉莉太平洋化妆品美国站:Amore Pacific US
2016/10/28 全球购物
ABOUT YOU罗马尼亚:超过600个时尚品牌
2019/09/19 全球购物
《童趣》教学反思
2014/02/19 职场文书
导师评语大全
2014/04/26 职场文书
文明演讲稿范文
2014/05/12 职场文书
2015年秘书个人工作总结
2015/04/25 职场文书
《艾尔登法环》1.03.3补丁上线 碎星伤害调整
2022/04/07 其他游戏
Java 死锁解决方案
2022/05/11 Java/Android
MySQL 自动填充 create_time 和 update_time
2022/05/20 MySQL