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 23 Python
深入解析Python中的descriptor描述器的作用及用法
Jun 27 Python
python计算auc指标实例
Jul 13 Python
django 发送手机验证码的示例代码
Apr 25 Python
django 环境变量配置过程详解
Aug 06 Python
pymysql模块的使用(增删改查)详解
Sep 09 Python
Python使用Opencv实现图像特征检测与匹配的方法
Oct 30 Python
python科学计算之numpy——ufunc函数用法
Nov 25 Python
Django高并发负载均衡实现原理详解
Apr 04 Python
python Matplotlib模块的使用
Sep 16 Python
python 逆向爬虫正确调用 JAR 加密逻辑
Jan 12 Python
详解在OpenCV中如何使用图像像素
Mar 03 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和MySQL保存和输出图片
2006/10/09 PHP
PHP安全的URL字符串base64编码和解码
2014/06/19 PHP
PHP上传图片类显示缩略图功能
2016/06/30 PHP
PHP Header失效的原因分析及解决方法
2016/11/16 PHP
php插入mysql数据返回id的方法
2018/05/31 PHP
jQuery实现原理的模拟代码 -6 代码下载
2010/08/16 Javascript
document.getElementById的简写方式(获取id对象的简略写法)
2010/09/10 Javascript
jQuery easyui datagrid动态查询数据实例讲解
2013/02/26 Javascript
jquery表格内容筛选实现思路及代码
2013/04/16 Javascript
用原生JavaScript实现jQuery的$.getJSON的解决方法
2013/05/03 Javascript
解决json日期格式问题的3种方法
2014/02/02 Javascript
JavaScript快速切换繁体中文和简体中文的方法及网站支持简繁体切换的绝招
2016/03/07 Javascript
jquery实现下拉框功能效果【实例代码】
2016/05/06 Javascript
jQueryUI DatePicker 添加时分秒
2016/06/04 Javascript
强大的JavaScript响应式图表Chartist.js的使用
2017/09/13 Javascript
vue双向数据绑定知识点总结
2018/04/18 Javascript
JavaScript中join()、splice()、slice()和split()函数用法示例
2018/08/24 Javascript
用Object.prototype.toString.call(obj)检测对象类型原因分析
2018/10/11 Javascript
将RGB值转换为灰度值的简单算法
2019/10/09 Javascript
python常见数制转换实例分析
2015/05/09 Python
python条件变量之生产者与消费者操作实例分析
2017/03/22 Python
django基础之数据库操作方法(详解)
2017/05/24 Python
Python 类的特殊成员解析
2018/06/20 Python
pycharm恢复默认设置或者是替换pycharm的解释器实例
2018/10/29 Python
python路径的写法及目录的获取方式
2019/12/26 Python
python判断变量是否为int、字符串、列表、元组、字典的方法详解
2020/02/13 Python
python字符串常用方法及文件简单读写的操作方法
2020/03/04 Python
什么是JNDI的上下文?如何初始化JNDI上下文
2012/03/10 面试题
服装厂厂长职责
2013/12/16 职场文书
员工培训邀请函
2014/02/02 职场文书
宾馆总经理岗位职责
2014/02/14 职场文书
2014年仓库工作总结
2014/11/20 职场文书
高三复习计划
2015/01/19 职场文书
劳动保障个人工作总结
2015/03/04 职场文书
2019年新郎保证书3篇
2019/10/17 职场文书
python缺失值的解决方法总结
2021/06/09 Python