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的绘图工具matplotlib使用实例
Jul 03 Python
Python编程语言的35个与众不同之处(语言特征和使用技巧)
Jul 07 Python
python实现ipsec开权限实例
Nov 11 Python
Python的Flask开发框架简单上手笔记
Nov 16 Python
python嵌套字典比较值与取值的实现示例
Nov 03 Python
详解python列表生成式和列表生成式器区别
Mar 27 Python
Python 3.8 新功能全解
Jul 25 Python
python3实现elasticsearch批量更新数据
Dec 03 Python
Python动态声明变量赋值代码实例
Dec 30 Python
Scrapy框架实现的登录网站操作示例
Feb 06 Python
Python fileinput模块如何逐行读取多个文件
Oct 05 Python
python基础之爬虫入门
May 10 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 ? EasyUI DataGrid 资料取的方式介绍
2012/11/07 PHP
PHP实现图片的等比缩放和Logo水印功能示例
2017/05/04 PHP
JavaScript 利用StringBuffer类提升+=拼接字符串效率
2009/11/24 Javascript
简短几句jquery代码的实现一个图片向上滚动切换
2011/09/02 Javascript
Jquery自定义button按钮的几种方法
2014/06/11 Javascript
jQuery中text() val()和html()的区别实例详解
2016/06/28 Javascript
javascript函数中的3个高级技巧
2016/09/22 Javascript
AngularJS实现星星等级评分功能
2016/09/24 Javascript
js实现彩色条纹滚动条效果
2017/03/15 Javascript
基于jQuery实现的Ajax 验证用户名唯一性实例代码
2017/06/28 jQuery
轻松玩转BootstrapTable(后端使用SpringMVC+Hibernate)
2017/09/06 Javascript
js解决软键盘遮挡输入框的问题分享
2017/12/19 Javascript
微信小程序实现多图上传
2020/06/19 Javascript
[48:53]2014 DOTA2华西杯精英邀请赛 5 25 LGD VS VG第一场
2014/05/26 DOTA
Python中字符串对齐方法介绍
2015/05/21 Python
Python3 处理JSON的实例详解
2017/10/29 Python
Python实现将HTML转成PDF的方法分析
2019/05/04 Python
简单了解Django ContentType内置组件
2019/07/23 Python
python实现人机猜拳小游戏
2020/02/03 Python
python实现跨excel sheet复制代码实例
2020/03/03 Python
Python如何对XML 解析
2020/06/28 Python
css3实现的多级渐变下拉菜单导航效果代码
2015/08/31 HTML / CSS
HTML5中的拖放实现详解
2017/08/23 HTML / CSS
健康监测猫砂:Pretty Litter
2017/05/25 全球购物
static函数与普通函数有什么区别
2015/12/25 面试题
廉政教育心得体会
2014/01/01 职场文书
租房协议书怎么写
2014/04/10 职场文书
干部考核评语
2014/04/29 职场文书
文秘自荐信
2014/06/28 职场文书
青春励志演讲稿范文
2014/08/25 职场文书
邮政竞聘演讲稿
2014/09/03 职场文书
院党委组织查摆问题对照检查材料思想汇报2014
2014/10/08 职场文书
小学生交通安全寄语
2015/02/27 职场文书
民警忠诚教育心得体会
2016/01/23 职场文书
python flappy bird小游戏分步实现流程
2022/02/15 Python
IIS服务器中设置HTTP重定向访问HTTPS
2022/04/29 Servers