最近看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. vs中使用M_PI的问题及解决 角度转弧度&根据弧度计算圆周上点的坐标的方法

    M_PI 是一个宏定义,圆周率的定义           C/C++ code #define M_PI 3.14159265358979323846 此宏定义和编译器有关,TC中M_PI宏就定义在& ...

  2. 使用IntelliJ IDEA 15和Maven创建Java Web项目(转)

    1. Maven简介 相对于传统的项目,Maven 下管理和构建的项目真的非常好用和简单,所以这里也强调下,尽量使用此类工具进行项目构建, 它可以管理项目的整个生命周期. 可以通过其命令做所有相关的工 ...

  3. special points about git

    1 about "origin/master tracks the remote branch" 1.1 what does tracking mean? after " ...

  4. IIS的ARR实现站点的负载均衡 nginx 对比

    windows下使用IIS的ARR实现站点的负载均衡 - CSDN博客 https://blog.csdn.net/zzy7075/article/details/73294713 IIS的ARR实现 ...

  5. vue如何做分页?

    原创作品转载请注明出处 先来看一下效果图:    功能描述: 1. 点击页面序号跳转到相应页面: 2. 点击单左/单右,向后/向前跳转一个页面: 3. 点击双左/双右,直接跳转到最后一页/第一页: 3 ...

  6. Wix Burn:如何将32位和64位的安装包制作成一个安装包

    由于Windows Installer不是平台独立的(即区分32-bit和64-bit),因此用Wix制作的安装包在编译不能像.net应用那样采用Any CPU编译,而必须制定是目标Platform是 ...

  7. hdu5325 树的思维题

    pid=5325">http://acm.hdu.edu.cn/showproblem.php? pid=5325 Problem Description Bobo has a tre ...

  8. ceph pool 管理

    创建池 [root@node1 ~]# ceph osd pool create monitor pool 'monitor' created 查看池 [root@node1 ~]# ceph osd ...

  9. SAP采购寄售业务操作步骤

    [转自 http://blog.sina.com.cn/s/blog_6466e5f70100jghg.html] 这里所示的是比较完整的步骤,包含了:信息记录.采购合同.货源清单.采购申请.采购订单 ...

  10. 如何修改硬盘挂载的名字LABEL

    ➜ ~ df -h Filesystem Size Used Avail Use% Mounted on/dev/sda2 114G 97G 12G 90% /media/brian/4ef34b75 ...