最近看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参数的不同,调用不同的函数实现几种格式的输出

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_Python中的getattr()函数详解相关推荐

  1. python getattr_Python中的getattr()函数详解:

    标签:Python中的getattr()函数详解: getattr(object, name[, default]) -> value Get a named attribute from an ...

  2. python getattr函数_Python中的getattr()函数详解

    在计算机编程中,自省是指这种能力:检查某些事物以确定它是什么.它知道什么以及它能做什么.自省向程序员提供了极大的灵活性和控制力. 自省(introspection),在计算机编程领域里,是指在运行时来 ...

  3. python getattr函数_[转]Python中的getattr()函数详解

    看了下函数本身的doc getattr(object, name[, default]) -> value Get a named attribute from an object; getat ...

  4. python 闭包中的匿名函数详解!

    匿名函数 孔子曰:温故而知新,可以为师矣. 天若有情天亦老,人间正道是沧桑. Python–lambda表达式 lambda表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就 ...

  5. python input函数详解_对Python3中的input函数详解

    下面介绍python3中的input函数及其在python2及pyhton3中的不同. python3中的ininput函数,首先利用help(input)函数查看函数信息: 以上信息说明input函 ...

  6. Python中的bbox_overlaps()函数详解

    Python中的bbox_overlaps()函数详解 想要编写自己的目标检测算法,就需要掌握bounding box(边界框)之间的关系.在这之中,bbox_overlaps()函数是一个非常实用的 ...

  7. timm 视觉库中的 create_model 函数详解

    timm 视觉库中的 create_model 函数详解 最近一年 Vision Transformer 及其相关改进的工作层出不穷,在他们开源的代码中,大部分都用到了这样一个库:timm.各位炼丹师 ...

  8. java的匿名函数_JAVA语言中的匿名函数详解

    本文主要向大家介绍了JAVA语言中的匿名函数详解,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助. 一.使用匿名内部类 匿名内部类由于没有名字,所以它的创建方式有点儿奇怪.创建格式如下: ...

  9. python open写入_Python3 open() 函数详解 读取文件写入文件追加文件二进制文件

    Python3 open() 函数详解 读取文件写入文件追加文件二进制文件 open()函数的主要作用是打开文件并返回相应文件对象,使用文件对象可以对当前文件进行读取.写入.追加等操作,默认情况下&q ...

最新文章

  1. Android 手机适配
  2. 基于双向LSTM和迁移学习的seq2seq核心实体识别
  3. Construct Binary Tree from Inorder and Postorder Traversal
  4. python nodemcu_python开发nodemcu(一)
  5. 数学教育中的AI:NeurIPS’21 Workshop 欢迎投稿!
  6. 2020年12月最新OneDrive网盘免费领取5TB教程
  7. r语言数据变量分段_使用R语言实现数据分段
  8. 线上讲座——全国海关中心架构师王翔畅谈设计模式
  9. jsp,mysql乱码情况1
  10. 【Shell】ps -ef 和ps aux
  11. 一加8t(oneplus 8t)通过9008救砖
  12. 【BCM】博通 linux-4.19 gcc-9.2 toolchain 环境搭建
  13. 不同时区时间换算_世界时区划分时差在线查询计算_时间换算器
  14. Python 【问题描述】按照世卫组织的标准: 男性:(身高cm-80)×70%=标准体重 女性:(身高cm-70)×60%=标准体重 标准体重正负10%为正常体重(含10%) 标准体重正负1
  15. python_opencv 黑白图片之白色部分单独分离
  16. win7TTS修复,使用C#SpeechSynthesizer 类
  17. vue使用高德地图的搜索地址和拖拽选址
  18. redis放入对象的几种方式
  19. 金蝶物料辅助属性改造
  20. 剑指 Offer 41-50

热门文章

  1. Java中string字符串的值_Java中的字符串(String)
  2. 【大学到研究生自学Java的学习路线】这是一份最适合普通大众、非科班的路线,帮你快速找到一份满意的工作
  3. 如何开发自己的第1个可以上线的Java项目?
  4. 手撕 MySQL 事务,发生了什么?
  5. java基础(十) 深入理解数组类型
  6. go linux环境搭建,Linux 下 Go 环境搭建以及 Gin 安装
  7. oracle+手工创建pfile,oracle 手工创建数据库
  8. curl head请求_CURL速查
  9. 基于OpenResty的弹性网关实践(二)
  10. Activiti工作流之网关