最近看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. tao.opengl+C#绘制三维模型

    一.tao.Opengl技术简介 Opengl是一种C风格的图形库,即opengl中没有类和对象,只有大量的函数.Opengl在内部就是一个状态机,利用不同的函数来修改opengl状态机的状态,以达到 ...

  2. python文件读写方式

    window下换行\r\n linux.unix.mac下都是\n - 以二进制的形式wb写入,同样以二进制的方式读取rb ``` f = open('file name','wb') f.write ...

  3. 关于TransactionScope 使用

    在去年的项目中使用了TransactionScope,现在总结下TransactionScope的使用说明 一.TransactionScope是.Net Framework 2.0之后,新增了一个名 ...

  4. ThreadLocal的简单使用

    package com.thread; public class ThreadLocalTest { public static void main(String[] args) { final Pe ...

  5. 九度OJ 1073:杨辉三角形 (递归)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:3780 解决:1631 题目描述: 输入n值,使用递归函数,求杨辉三角形中各个位置上的值. 输入: 一个大于等于2的整型数n 输出: 题目可 ...

  6. Hibernate连接池设置

    在公司第一次做项目放到服务器上测试,发现每隔一段时间不用数据库就连接不上了(以前学过连接池,很久没用就忘了),在myeclipse上的时候没发现,网上搜索才发现是hibernate连接池配置问题. 1 ...

  7. jxl java工具类,导出excel,导入数据库

    1: 引入jxl jar 我使用的为maven管理, <!--Excel工具--> <dependency> <groupId>net.sourceforge.je ...

  8. 开源Flex Air版免费激情美女视频聊天室,免费网络远程视频会议系统((Flex,Fms3联合打造))

    开源Flex Air版免费激情美女视频聊天室,免费网络远程视频会议系统((Flex,Fms3联合打造))   Flex,Fms3系列文章导航 Flex,Fms3相关文章索引 本篇是视频聊天,会议开发实 ...

  9. Java for LeetCode 117 Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

  10. iOS 分享功能开发

    iOS 开发过程中可能会遇到需要进行第三方分享的需求,比如向QQ,微信,微博等分享 如下图 我们今天要讲到的方式是使用了一个第三方工具: http://www.sharesdk.cn 一,注册账号 去 ...