Python中的getattr()函数详解
最近看Dive into python第四章自省中提到getattr()函数,作为一个内建函数平时自己没怎么用过所以也不太理解这个函数的一些用法
看了下函数本身的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参数的不同,调用不同的函数实现几种格式的输出
1
2
3
4
|
import
def
format = "text" ): output_function = getattr (statsout, "output_%s" % format ) return output_function(data) |
这个例子中可以根据传入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:
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中的getattr()函数详解的更多相关文章
- python中的buildin函数详解(第一篇)
这会是很长的一个帖子,因为我打算从python最基础的东西开始,尝试去完全的掌握它,buildin中有一些常用的函数比如 abs, open, setattr, getattr, 大家都很了解他们的用 ...
- python中的 zip函数详解
python中zip()函数用法举例 定义:zip([iterable, ...]) zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple ...
- python中的builtin函数详解-第二篇
classmethod(function) 这里不过多说明这个builtin方法的具体用法,python的文档和help函数已经给了这个方法充足的使用说明,所以我这里要说的时关于 classmetho ...
- 75.Python中ORM聚合函数详解:Sum
Sum:某个字段的总和. 1. 求图书的销售总额,示例代码如下: from django.http import HttpResponse from django.db import connecti ...
- 72.Python中ORM聚合函数详解:Avg,aggregate,annotate
聚合函数: 如果你用原生SQL语句,则可以使用聚合函数提取数据.比如提取某个商品销售的数量,那么就可以使用Count,如果想要知道销售的平均价格,那么就可以使用Avg. 聚合函数是通过aggregat ...
- 74.Python中ORM聚合函数详解:Max,Min
Max和Min:获取指定对象的最大值和最小值. 1. 比如:想要获取Author表中的最大的年龄和最小的年龄.示例代码如下: from django.http import HttpResponse ...
- 73.Python中ORM聚合函数详解:Count
Count:用来求某个数据的个数. 在以下所有的示例中所采用的模型为: from django.db import models # 定义作者模型 class Author(models.Model) ...
- Python中的高级数据结构详解
这篇文章主要介绍了Python中的高级数据结构详解,本文讲解了Collection.Array.Heapq.Bisect.Weakref.Copy以及Pprint这些数据结构的用法,需要的朋友可以参考 ...
- Python中格式化format()方法详解
Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任何东西都是对象; 字符串的参 ...
随机推荐
- Drcom账户管理Server端解说
https://www.github.com/xiyouMc 首先今天要讲的是针对Drcom查询账户URL的解析和抓取数据. Drcom是大学生宿舍上网普遍使用的联网client,然而对于自己账 ...
- smarty静态缓存
缓存能让程序访问起来更加快速,调数据库的数量变少,不能实时的跟数据库同步, 一般缓存文件都放在smarty文件下cach文件夹中: 建立缓存的PHP和HTML文件: 先编辑PHP文件来查询显示数据库当 ...
- 玩家下线(GS部分)
玩家下线,之前一直感觉这个过程有点复杂 else if (stat == link_stat::link_disconnected || stat == link_stat::link_connect ...
- Swift 学习笔记 (类和结构体)
类和结构体是一种多功能且灵活的构造体.通过使用与现存常量 变量 函数完全相同的语法来在类和结构体中定义属性和方法以添加功能. Swift中不需要你为自定义的类和结构体创建独立的结构和实现文件.在Swi ...
- gitPermission denied (publickey).
$ git clone git@github.com:DavidWanderer/test1.git Cloning into 'test1'... Warning: Permanently adde ...
- 前端JSONPJIE解决跨域问题
解决同源策略的两个方法 1 . JSONP jsonp (将 JSON 数据填充进回调函数,这就是JSONP的JSON+Padding 的含义) jsonp是json用来跨域的一个东西,原理是通过sc ...
- BZOJ 4523 [Cqoi2016]路由表 Trie树
Trie树的应用题目. 在线建立一棵01 Trie树,然后按照要求用询问在上面跑,用单调栈维护答案即可. #include<iostream> #include<cstdio> ...
- vue 升降排序
本实例是根据工作进度的百分比来进行排序. html <div class="ibox-content"> <li v-for="(rangeItem,i ...
- jQuery选项卡tabulous
jQuery选项卡tabulous,jQuery,选项卡,tab标签切换代码,扁平设计,jQuery选项卡tabulous是一款支持Scale.Slide.Scale Up.Flip等效果jquery ...
- HDU 3853 LOOPS:期望dp【网格型】
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3853 题意: 有一个n*m的网格. 给出在每个格子时:留在原地.向右走一格,向下走一格的概率. 每走一 ...