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计算圆周长、面积、球体体积并画出圆
Apr 08 Python
Python写的PHPMyAdmin暴力破解工具代码
Aug 06 Python
Python实现Const详解
Jan 27 Python
Python 中的with关键字使用详解
Sep 11 Python
用不到50行的Python代码构建最小的区块链
Nov 16 Python
python增加矩阵维度的实例讲解
Apr 04 Python
Python绘制3D图形
May 03 Python
python中退出多层循环的方法
Nov 27 Python
Pytorch 保存模型生成图片方式
Jan 10 Python
Python正则表达式如何匹配中文
May 27 Python
pycharm软件实现设置自动保存操作
Jun 08 Python
Python使用内置函数setattr设置对象的属性值
Oct 16 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
删除及到期域名的查看(抢域名必备哦)
2008/05/14 PHP
解析使用ThinkPHP应该掌握的调试手段
2013/06/20 PHP
php 升级到 5.3+ 后出现的一些错误,如 ereg(); ereg_replace(); 函数报错
2015/12/07 PHP
用PHP做了一个领取优惠券活动的示例代码
2019/07/05 PHP
JS获取父节点方法
2009/08/20 Javascript
JavaScript 面向对象的之私有成员和公开成员
2010/05/04 Javascript
JavaScript 联动的无限级封装类,数据采用非Ajax方式,随意添加联动
2010/06/29 Javascript
ASP.NET MVC中EasyUI的datagrid跨域调用实现代码
2012/03/14 Javascript
Javascript异步编程的4种方法让你写出更出色的程序
2013/01/17 Javascript
html向js方法传递参数具体实现
2013/08/08 Javascript
JS中typeof与instanceof之间的区别总结
2013/11/14 Javascript
js中匿名函数的创建与调用方法分析
2014/12/19 Javascript
JS中setTimeout的巧妙用法前端函数节流
2016/03/24 Javascript
AngularJs表单验证实例代码解析
2016/11/29 Javascript
AngularJS实现给动态生成的元素绑定事件的方法
2016/12/14 Javascript
移动端效果之IndexList详解
2017/10/20 Javascript
再谈Angular4 脏值检测(性能优化)
2018/04/23 Javascript
原生js实现each方法实例代码详解
2019/05/27 Javascript
js get和post请求实现代码解析
2020/02/06 Javascript
[31:00]2014 DOTA2华西杯精英邀请赛5 24 NewBee VS iG
2014/05/25 DOTA
python调用java模块SmartXLS和jpype修改excel文件的方法
2015/04/28 Python
基于windows下pip安装python模块时报错总结
2018/06/12 Python
Django框架验证码用法实例分析
2019/05/10 Python
python 绘制拟合曲线并加指定点标识的实现
2019/07/10 Python
使用Python实现Wake On Lan远程开机功能
2020/01/22 Python
使用HTML5 IndexDB存储图像和文件的示例
2018/11/05 HTML / CSS
英国折扣高尔夫商店:Discount Golf Store
2019/11/19 全球购物
电子狗项圈:eDog Australia
2019/12/04 全球购物
法国购买二手电子产品网站:Asgoodasnew
2020/03/27 全球购物
会计找工作求职信范文
2013/12/09 职场文书
投资意向协议书
2015/01/29 职场文书
佛光寺导游词
2015/02/10 职场文书
教师党员个人总结
2015/02/10 职场文书
幼儿园父亲节活动总结
2015/02/12 职场文书
志愿者个人总结
2015/03/03 职场文书
Python import模块的缓存问题解决方案
2021/06/02 Python