最近看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
statsout 
def
output(data,
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()函数详解的更多相关文章

  1. python中的buildin函数详解(第一篇)

    这会是很长的一个帖子,因为我打算从python最基础的东西开始,尝试去完全的掌握它,buildin中有一些常用的函数比如 abs, open, setattr, getattr, 大家都很了解他们的用 ...

  2. python中的 zip函数详解

    python中zip()函数用法举例 定义:zip([iterable, ...]) zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple ...

  3. python中的builtin函数详解-第二篇

    classmethod(function) 这里不过多说明这个builtin方法的具体用法,python的文档和help函数已经给了这个方法充足的使用说明,所以我这里要说的时关于 classmetho ...

  4. 75.Python中ORM聚合函数详解:Sum

    Sum:某个字段的总和. 1. 求图书的销售总额,示例代码如下: from django.http import HttpResponse from django.db import connecti ...

  5. 72.Python中ORM聚合函数详解:Avg,aggregate,annotate

    聚合函数: 如果你用原生SQL语句,则可以使用聚合函数提取数据.比如提取某个商品销售的数量,那么就可以使用Count,如果想要知道销售的平均价格,那么就可以使用Avg. 聚合函数是通过aggregat ...

  6. 74.Python中ORM聚合函数详解:Max,Min

    Max和Min:获取指定对象的最大值和最小值. 1. 比如:想要获取Author表中的最大的年龄和最小的年龄.示例代码如下: from django.http import HttpResponse ...

  7. 73.Python中ORM聚合函数详解:Count

    Count:用来求某个数据的个数. 在以下所有的示例中所采用的模型为: from django.db import models # 定义作者模型 class Author(models.Model) ...

  8. Python中的高级数据结构详解

    这篇文章主要介绍了Python中的高级数据结构详解,本文讲解了Collection.Array.Heapq.Bisect.Weakref.Copy以及Pprint这些数据结构的用法,需要的朋友可以参考 ...

  9. Python中格式化format()方法详解

    Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任何东西都是对象; 字符串的参 ...

随机推荐

  1. 模式识别之svm()---支持向量机svm 简介1995

    转自:http://www.blogjava.net/zhenandaci/archive/2009/02/13/254519.html 作者:Jasper 出自:http://www.blogjav ...

  2. python 基础 3.1 打开文件 a a+ r+ w+ 详解

      一.python 访问文件   1.在python中要访问文件,首先要打开文件,也就是open ---open   r:  只读   w:  只写 ,文件已存在则清空,不存在则创建   a:追加 ...

  3. EasyNVR无插件流媒体服务器前端技术防止重复提交的方法

    现在随着接触EasyNVR时间越来越长,越发的觉得EasyNVR真的是一个"神器".从功能上来说自身不仅可以拉出来使用(具体功能搜索EasyNVR一定有惊喜!),也可以作为设备端与 ...

  4. EasyDarwin支持GB28181协议开发

    本文转自:http://blog.csdn.net/gavin1010/article/details/77926853 EasyGB28181服务器开发 背景 当前的安防行业,除了私有协议,普遍使用 ...

  5. 九度OJ 1019:简单计算器 (基础题、DP)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:6725 解决:2454 题目描述:     读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值. 输入:     ...

  6. Mac root Operation not permitted

      在mac下sudo 拷贝和删除文件时提醒Operation not permitted. 网上查了一些资料,需要执行 chflags nouchg /path/to/item 命令. 赶紧照做, ...

  7. Django 初始化数据库

    django 初始化数据库 刷新数据库guoguos-MacBook-Pro:mysite guoguo$ python manage.py sqlflushBEGIN;SET FOREIGN_KEY ...

  8. struts 与 Java Web应用简介

    struts实质上就是JSP Model2的基础上实现的MVC框架. 在Struts框架中,模型有实现业务逻辑的JavaBean或EJB组件构成 视图由一组JSP文件构成. 控制器 控制器由Actio ...

  9. 在JavaScript中闭包的作用和简单的用法

    在JavaScript中闭包的作用和简单的用法 一.闭包的简介 作用域链:在js中只有函数有作用域的概念,由于函数内能访问函数外部的数据,而函数外部不能访问函数内部的数据,由上述形成一种作用域访问的链 ...

  10. nodejs搭建简单的websocket服务端

    创建websocket服务端使用了nodejs-websocket ,首先要安装nodejs-websocket,在项目的目录下: npm install nodejs-websocket 1.搭建w ...