python中的内置函数getattr()介绍及示例


Posted in Python onJuly 20, 2014

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

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”是对对象属性的名称,则返回对应属性的值。

'# -*- 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')

 这段代码执行的结果是:

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.我需要在一个类中动态添加其它类中有的方法:

#如果类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())

我们只需要:

a = A()

b = B()

a.addnewattributesfromotherclass(b)

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

Python 相关文章推荐
十条建议帮你提高Python编程效率
Feb 16 Python
详解Python中的Numpy、SciPy、MatPlotLib安装与配置
Nov 17 Python
django初始化数据库的实例
May 27 Python
Python OpenCV处理图像之图像像素点操作
Jul 10 Python
解决使用export_graphviz可视化树报错的问题
Aug 09 Python
numpy.random.shuffle打乱顺序函数的实现
Sep 10 Python
Python3 A*寻路算法实现方式
Dec 24 Python
简单了解python filter、map、reduce的区别
Jan 14 Python
python实现密码验证合格程序的思路详解
Jun 01 Python
python如何使用代码运行助手
Jul 03 Python
python中altair可视化库实例用法
Jan 26 Python
Python实战之实现简易的学生选课系统
May 25 Python
Python实现的生成自我描述脚本分享(很有意思的程序)
Jul 18 #Python
Python中使用 Selenium 实现网页截图实例
Jul 18 #Python
Python中使用PyHook监听鼠标和键盘事件实例
Jul 18 #Python
python中使用pyhook实现键盘监控的例子
Jul 18 #Python
python使用pyhook监控键盘并实现切换歌曲的功能
Jul 18 #Python
python中使用百度音乐搜索的api下载指定歌曲的lrc歌词
Jul 18 #Python
python采集博客中上传的QQ截图文件
Jul 18 #Python
You might like
一些常用的php函数
2006/12/06 PHP
php中截取中文字符串的代码小结
2011/07/17 PHP
php实现快速排序法函数代码
2012/08/27 PHP
php遍历目录输出目录及其下的所有文件示例
2014/01/27 PHP
ThinkPHP调用common/common.php函数提示错误function undefined的解决方法
2014/08/25 PHP
PHP程序员常见的40个陋习,你中了几个?
2014/11/20 PHP
ThinkPHP中__initialize()和类的构造函数__construct()用法分析
2014/11/29 PHP
在chrome中window.onload事件的一些问题
2010/03/01 Javascript
JavaScript中使用构造函数实现继承的代码
2010/08/12 Javascript
多个datatable共存造成多个表格的checkbox都被选中
2013/07/11 Javascript
Javascript和HTML5利用canvas构建Web五子棋游戏实现算法
2013/07/17 Javascript
js采用map取到id集合组并且实现点击一行选中一行
2013/12/16 Javascript
Javascript中的String对象详谈
2014/03/03 Javascript
判断浏览器的内核及版本号方法汇总
2015/01/05 Javascript
浅析JS中常用类型转换及运算符表达式
2017/07/23 Javascript
webpack打包node.js后端项目的方法
2018/03/10 Javascript
AJAX在JQuery中的应用详解
2019/01/30 jQuery
JavaScript数据结构与算法之检索算法示例【二分查找法、计算重复次数】
2019/02/22 Javascript
JS浏览器BOM常见操作实例详解
2020/04/27 Javascript
[02:05]DOTA2完美大师赛趣味视频之看我表演
2017/11/18 DOTA
[58:57]2018DOTA2亚洲邀请赛3月29日小组赛B组 Effect VS VGJ.T
2018/03/30 DOTA
[01:02:07]Liquid vs Newbee 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/16 DOTA
浅析Python的Django框架中的Memcached
2015/07/23 Python
Python数组定义方法
2016/04/13 Python
python实现小球弹跳效果
2019/05/10 Python
查看Python依赖包及其版本号信息的方法
2019/08/13 Python
python web框架 django wsgi原理解析
2019/08/20 Python
pytorch sampler对数据进行采样的实现
2019/12/31 Python
Python Pillow(PIL)库的用法详解
2020/09/19 Python
加拿大鞋子连锁店:Town Shoes
2016/09/26 全球购物
先进集体获奖感言
2014/02/13 职场文书
党政领导班子四风问题对照检查材料思想汇报
2014/10/02 职场文书
银行开户授权委托书格式
2014/10/10 职场文书
群众路线教育实践活动学习笔记内容
2014/11/06 职场文书
人身损害赔偿协议书
2016/03/22 职场文书
TV动画《间谍过家家》公开PV
2022/03/20 日漫