在python的官方文档中:getattr()的解释如下:

1
2
3
getattr(object, name[, default])
 
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

根据属性名称返回对象值。如果“name”是对对象属性的名称,则返回对应属性的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'# -*- coding: utf-8 -*-'
 
__author__ = 'lucas'
 
class attrtest(object):
 
  def __init__(self):
    pass
 
  def trygetattr0(self):
    self.name = 'lucas'
    print self.name
    #equals to self.name
    print getattr(self,'name')
 
  def attribute1(self,para1):
    print 'attribute1 called and '+ para1+' is passed in as a parameter'
 
  def trygetattr(self):
    fun = getattr(self,'attribute1')
    print type(fun)
    fun('crown')
 
if __name__=='__main__':
  test = attrtest()
  print 'getattr(self,\'name\') equals to self.name '
  test.trygetattr0()
  print 'attribute1 is indirectly called by fun()'
  test.trygetattr()
  print 'attrribute1 is directly called'
  test.attribute1('tomato')

这段代码执行的结果是:

1
2
3
4
5
6
7
8
9
10
getattr(self,'name') equals to self.name
lucas
lucas
attribute1 is indirectly called by fun()
<type 'instancemethod'>
attribute1 called and crown is passed in as a parameter
attrribute1 is directly called
attribute1 called and tomato is passed in as a parameter
 
Process finished with exit code 0

第一个函数tryattribute0()非常好理解,就如同定义里说的一样。第二个函数tryattribute1()就有一点费解了。其实原理并不复杂,我们看到fun的type是 instancemethod,这里你可以认为:对于函数,getattr()的返回值是一个指针,指针赋值给接受它的变量,以后call这个变量就等于调用变量指向的函数。

原理我们知道了,那getattr的作用是什么呢?

你熟悉java或者c#中的反射么?反射的一个重要作用就是延迟加载,这样可以解耦,这样可以让系统运行的更有效率。作为动态语言,python显然在这方面要更加强大,

getattr()就是实现python反射的一块积木,结合其它方法如setattr(),dir() 等,我们可以做出很多有趣的事情。

我们看以下场景:

1.我需要在一个类中动态添加其它类中有的方法:

1
2
3
4
5
6
7
#如果类A中有如下方法:
def addnewattributesfromotherclass(self,class_name):
    func_names = dir(class_name)
    for func_name in func_names:
      if not func_name.startswith('_'):
        new_func = getattr(class_name,func_name)
        self.__setattr__(func_name,new_func())

我们只需要:

1
2
3
4
5
a = A()
 
b = B()
 
a.addnewattributesfromotherclass(b)

这样a就可以调用B中的'非私有'方法啦。

python中的内置函数getattr()介绍及示例的更多相关文章

  1. python中的内置函数getattr()

    在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the named attribu ...

  2. python中一些内置函数实例

    lambda表达式 简单函数可用lambda表达式 1. def f1() return(123) r1=f1() print() 2. f2=lambda:123 r2=f2() print() 以 ...

  3. python中的内置函数(一)

    内置函数:内置函数就是python提供的,可以拿来直接用的函数 作用域相关 locals():返回当前作用域中的名字globals():返回全局作用域中的内容 def func(): print('我 ...

  4. Python中的内置函数__init__()的理解

    有点意思,本来我是学习java的.总所周知,java也有构造函数,而python在面向对象的概念中,也有构造函数.它就是 __init__(self) 方法. 其实类似于__init__()这种方法, ...

  5. python中的内置函数,递归,递归文件显示(二),二分法

    1.部分内置函数 repr()显示出字符串的官方表示形式,返回一个对象的string形式 # repr 就是原封不动的输出, 引号和转义字符都不起作用 print(repr('大家好,\n \t我叫周 ...

  6. python中的内置函数(一), lambda, filter, map

    https://www.processon.com/view/link/5c10da0ce4b099ae3e137bf6 1.内置函数 内置函数就是python中提供的,可以直接拿来用的函数,比如pr ...

  7. python中的内置函数(2)

    一.lambda匿名函数定义:为了解决一些简单的需求而设计的一句话函数例子:计算n的n次方 def func(n):#正常的写法 return n**2 f=lambda n:n**2 这里的lamb ...

  8. 2018.8.14 python中的内置函数(68个)

    主要内容: python中68个内置函数的功能及使用方法

  9. python学习之【第十篇】:Python中的内置函数

    1.前言 内置函数,就是Python内部预先定义好的函数,可以直接使用,Python中内置函数有以下这么多个: 2.map() 描述: map() 会根据提供的函数对指定序列做映射.第一个参数 fun ...

随机推荐

  1. excel 常用函数和实现功能经验总结积累

    0.判断一个文本字符串中是否包含数字!/判断一个文本字符串是否是纯汉字! 公式=IF(LENB(A1)=2*LEN(A1),”都是汉字“,“含有非汉字字符”) 解释函数: LEN(A1)#返回文本字符 ...

  2. spring cloud 初体验

    spring cloud分为注册端.客户端以及消费端 初体验的理解就是: 注册端就是将之前所有的应用在这边进行注册,然后给每个应用都生成自己的标识,这些应用就是来自于客户端,消费端则通过调用注册端(有 ...

  3. sql学习书籍

    SQL 入门 在准备成为MySQL DBA之前,能熟练的编写SQL是一个必要条件.exists 和 join之间的等价转换:基本的行列转换:SQL 循环等的熟练掌握对之后的运维和调优工作都有很大的帮助 ...

  4. sass报 error (Line XX: Invalid GBK character "\xE4") 的解决办法

    在webstorm配置的SASS,插入中文注释报错: cmd.exe /D /C call D:\ProgramFiles\Ruby24-x64\bin\sass.bat --no-cache --u ...

  5. loadrunner中组合场景的应用

    进行性能测试的回归测试时,可以设置组合场景,例如: 这时可以以组的形式运行: 运行效果如下: 当login运行完成后,运行goodslist脚本 . 运行时可以查看运行用户数.事务平均响应时间.吞吐量 ...

  6. [原][杂谈]如果人类的末日:"天网"出现

    本文由南水之源在2019年3月21日发布,转载需声明原作者 本文仅为一次基于科技发展与科幻小说的幻想,如果天网真的出现,请不要参考这篇逻辑破败的推论. 参考: 天网(Skynet),是电影<终结 ...

  7. 自定义 Cordova插件(基础篇)

    cordova自定义插件 注意:存放自定义cordova插件目录不能有空格可能会报错 cordova的安装 下载node.js,安装完成后你可以在命令行中使用node和npm. 安装cordova使用 ...

  8. 浙江省住房和城乡建设厅 http://www.zjjs.com.cn/ 漏洞提示

    http://220.189.211.52/zjjsgbxx/FileAttach/96dcdf11-c45e-4455-a443-f6dea8a44e23.html 可以下载,浏览 改修,

  9. arcpy简单示例

    最好在arcmap内置python模块运行. 这里用的是Zonel Stastic as Table模块,计算各个国家的逐月径流量的统计数据.需要对数百个tiff进行计算和导出,使用arcpy可以大大 ...

  10. 网络爬虫&起点中文网完本榜500部小说

    # 网络爬虫爬取起点中文网完本榜小说500部# 四步,分步操作,不易出错# 所需要获取的数据:书名 .作者.网址.类型.主要介绍.作品信息 from urllib.request import * # ...