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 29 Python
记录Django开发心得
Jul 16 Python
使用Python写个小监控
Jan 27 Python
python动态加载包的方法小结
Apr 18 Python
python脚本爬取字体文件的实现方法
Apr 29 Python
使用python根据端口号关闭进程的方法
Nov 06 Python
Python 利用pydub库操作音频文件的方法
Jan 09 Python
更新修改后的Python模块方法
Mar 03 Python
使用Python操作FTP实现上传和下载的方法
Apr 01 Python
python实现坦克大战游戏 附详细注释
Mar 27 Python
pyQT5 实现窗体之间传值的示例
Jun 20 Python
python实现修改固定模式的字符串内容操作示例
Dec 30 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
4月1日重磅发布!《星际争霸II》6.0.0版本更新
2020/04/09 星际争霸
PHP 获取MySQL数据库里所有表的实现代码
2011/07/13 PHP
php自定义分页类完整实例
2015/12/25 PHP
简单的pgsql pdo php操作类实现代码
2016/08/25 PHP
jquery ajax同步异步的执行最终解决方案
2013/04/26 Javascript
基于jquery的网站幻灯片切换效果焦点图代码
2013/09/15 Javascript
12306验证码破解思路分享
2015/03/25 Javascript
在JavaScript中对HTML进行反转义详解
2016/05/18 Javascript
详解nodejs通过代理(proxy)发送http请求(request)
2017/09/22 NodeJs
create-react-app中添加less支持的实现
2019/11/15 Javascript
vue实现商品列表的添加删除实例讲解
2020/05/14 Javascript
JS数据类型分类及常用判断方法
2020/11/19 Javascript
详解Django中的form库的使用
2015/07/18 Python
尝试用最短的Python代码来实现服务器和代理服务器
2016/06/23 Python
python merge、concat合并数据集的实例讲解
2018/04/12 Python
对django views中 request, response的常用操作详解
2019/07/17 Python
Python人工智能之路 之PyAudio 实现录音 自动化交互实现问答
2019/08/13 Python
Python爬虫实现使用beautifulSoup4爬取名言网功能案例
2019/09/15 Python
用什么库写 Python 命令行程序(示例代码详解)
2020/02/20 Python
解决 jupyter notebook 回车换两行问题
2020/04/15 Python
python简单利用字典破解zip文件口令
2020/09/07 Python
Python离线安装各种库及pip的方法
2020/11/28 Python
Python3爬虫RedisDump的安装步骤
2021/02/20 Python
CSS+jQuery+PHP+MySQL实现的在线答题功能
2015/04/25 HTML / CSS
全方位了解CSS3的Regions扩展
2015/08/07 HTML / CSS
size?爱尔兰官方网站:英国伦敦的球鞋精品店
2019/03/31 全球购物
新员工欢迎词
2014/01/12 职场文书
生日礼品店创业计划书范文
2014/03/21 职场文书
就业协议书的作用
2014/04/11 职场文书
汽车技术服务与贸易专业求职信
2014/07/20 职场文书
防灾减灾宣传标语
2014/10/07 职场文书
群众路线教育实践活动整改方案(个人版)
2014/10/25 职场文书
2015年秋季运动会加油稿
2015/07/22 职场文书
CSS变量实现主题切换的方法
2021/06/23 HTML / CSS
javascript的var与let,const之间的区别详解
2022/02/18 Javascript
Python 数据可视化工具 Pyecharts 安装及应用
2022/04/20 Python