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的Django框架中的templates设置
May 11 Python
Python脚本简单实现打开默认浏览器登录人人和打开QQ的方法
Apr 12 Python
实现python版本的按任意键继续/退出
Sep 26 Python
微信跳一跳辅助python代码实现
Jan 05 Python
python使用Matplotlib画条形图
Mar 25 Python
对Python中list的倒序索引和切片实例讲解
Nov 15 Python
浅谈PYTHON 关于文件的操作
Mar 19 Python
对Python中TKinter模块中的Label组件实例详解
Jun 14 Python
Django 外键的使用方法详解
Jul 19 Python
pygame实现俄罗斯方块游戏(基础篇3)
Oct 29 Python
python集合的新增元素方法整理
Dec 07 Python
如何利用Python实现n*n螺旋矩阵
Jan 18 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
PHP5.0对象模型探索之抽象方法和抽象类
2006/09/05 PHP
php 无限级 SelectTree 类
2009/05/19 PHP
php5.3 废弃函数小结
2010/05/16 PHP
PHP中extract()函数的定义和用法
2012/08/17 PHP
PHP采用自定义函数实现遍历目录下所有文件的方法
2014/08/19 PHP
PHP闭包函数传参及使用外部变量的方法
2016/03/15 PHP
php使用redis的几种常见操作方式和用法示例
2020/02/20 PHP
JavaScript 异步调用框架 (Part 1 - 问题 &amp; 场景)
2009/08/03 Javascript
jQuery选择没有colspan属性的td的代码
2010/07/06 Javascript
疯狂Jquery第一天(Jquery学习笔记)
2012/05/11 Javascript
使用JavaScript动态设置样式实现代码及演示动画
2013/01/25 Javascript
jQuery文本框(input textare)事件绑定方法教程
2013/04/24 Javascript
Javascript实现飞动广告效果的方法
2015/05/25 Javascript
jQuery获取页面元素绝对与相对位置的方法
2015/06/10 Javascript
JavaScript取得键盘按下方向键是哪个的方法
2015/08/04 Javascript
javascript比较语义化版本号的实现代码
2016/09/09 Javascript
KnockoutJS 3.X API 第四章之表单textInput、hasFocus、checked绑定
2016/10/11 Javascript
js模仿微信朋友圈计算时间显示几天/几小时/几分钟/几秒之前
2017/04/27 Javascript
vue.js 实现图片本地预览 裁剪 压缩 上传功能
2018/03/01 Javascript
详解如何在你的Vue项目配置vux
2018/06/04 Javascript
Node Express用法详解【安装、使用、路由、中间件、模板引擎等】
2020/05/13 Javascript
Openlayers实现距离面积测量
2020/09/28 Javascript
[03:57]2016完美“圣”典风云人物:rOtk专访
2016/12/09 DOTA
Python遍历指定文件及文件夹的方法
2015/05/09 Python
python模块之re正则表达式详解
2017/02/03 Python
解决Python3.5+OpenCV3.2读取图像的问题
2018/12/05 Python
Python操作Elasticsearch处理timeout超时
2020/07/17 Python
Bibloo奥地利:购买女装、男装、童装、鞋和配件
2018/10/18 全球购物
工程采购员岗位职责
2014/03/09 职场文书
《青蛙看海》教学反思
2014/04/23 职场文书
民用住房租房协议书
2014/10/29 职场文书
高效课堂教学反思
2016/02/24 职场文书
Oracle 区块链表创建过程详解
2021/05/15 Oracle
vue点击弹窗自动触发点击事件的解决办法(模拟场景)
2021/05/25 Vue.js
Python中OpenCV实现简单车牌字符切割
2021/06/11 Python
解析探秘fescar分布式事务实现原理
2022/02/28 Java/Android