python中getattr函数使用方法 getattr实现工厂模式
发布时间:2021-02-25 00:34:30
看了下函数本身的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)


猜你喜欢
- 上一次,我们谈到在ASP中如何利用“正则表达式”对象来实现各种数据的校验,文中描述了正则表达式对象的强大功能,接下来,我们来看看有关“正则表
- 一、什么是集成学习集成学习是一种技术框架,它本身不是一个单独的机器学习算法,而是通过构建并结合多个机器学习器来完成学习任务,一般结构是:先产
- setTimeoutsetTimeout 语法例子用 setTimeout 来执行 function不断重复执行的 setTimeout设定
- 1.文本框只能输入数字代码(小数点也不能输入)<input onkeyup="this.value=this.va
- 本文实例为大家分享了python调用百度语音REST API的具体代码,供大家参考,具体内容如下(百度的rest接口的部分网址发生了一定的变
- 摘要:不同方法读取excel中的多个不同sheet表格性能比较# 方法1def read_excel(path): df=pd.
- 背景App落地页迭代频繁,且需兼容App与各小App,目前是单向前进迭代,会存在以下问题:跳转原生交互;如:某个落地页增加了只有主App的才
- 学习前言……又看了很久的SSD算法,今天讲解一下训练部分的代码。预测部分的代码可以参照https
- 基本示例?计算属性允许我们声明性地计算衍生值。然而在有些情况下,我们需要在状态变化时执行一些“副作用&rdquo
- element-ui官网中关于行合并的例子是根据行号进行合并的,这显然不符合我们日常开发需求,因为通常我们table中的数据都是动态生成的,
- 前言今天给大家写一个个打地鼠小游戏,废话不多说直接开始~开发工具Python版本: 3.6.4相关模块:pygame模块;以及一些
- 我们使用tp或者yii2的时候,会将网站的前台和后台按照模块分组。yii2的高级模板已经帮我们划分好了,tp系列框架需要自己配置分组。那么l
- 本文实例讲述了python版本的读写锁操作方法。分享给大家供大家参考,具体如下:最近要用到读写锁的机制,但是python2.7的自带库里居然
- 目的实现字符串的左对齐,右对齐,居中对齐。方法 字符串内置了以下方法:其中width是指包含字符串S在内的宽度,fillchar默认是空格,
- 代码及注释如下#Auther Bob#--*--conding:utf-8 --*--#生产者消费者模型,这里的例子是这样的,有一个厨师在做
- 不同于其他软件项目,互联网项目的开发有其独有的特性。互联网项目开发不同于传统软件项目开发不同于需求定制性的软件开发公司。客户的需求是明确的,
- 1、 <script language="JavaScript"> javascript:window.hi
- 目录设计到的前端知识注册业务实现前端注册业务逻辑导入vue.js和ajax请求的js库准备register.js文件后端业务注册逻辑设计到的
- 简介🤔看了一圈,大家对 ts 封装 axios 都各有见解。但都不是我满意的吧,所以自己封装了一个💪。至于为什么敢叫最佳实践,因为我满意,就
- 前言特别说明: 本文只适合新手学习这篇文章带我们入门go语言的定义变量的方式,其实和javascript很相似,所以特意总结在此。在go语言