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可跨平台实现获取按键的方法
Mar 05 Python
Python实现类似jQuery使用中的链式调用的示例
Jun 16 Python
python 移除字符串尾部的数字方法
Jul 17 Python
Django中数据库的数据关系:一对一,一对多,多对多
Oct 21 Python
Python3爬虫教程之利用Python实现发送天气预报邮件
Dec 16 Python
python tkinter窗口最大化的实现
Jul 15 Python
基于Python 中函数的 收集参数 机制
Dec 21 Python
在django中使用apscheduler 执行计划任务的实现方法
Feb 11 Python
python实现马丁策略回测3000只股票的实例代码
Jan 22 Python
python文件名批量重命名脚本实例代码
Apr 22 Python
python基础学习之生成器与文件系统知识总结
May 25 Python
pytorch实现加载保存查看checkpoint文件
Jul 15 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函数http_build_query使用详解
2014/08/20 PHP
php使用cookie显示用户上次访问网站日期的方法
2015/01/26 PHP
php实现CSV文件导入和导出
2015/10/24 PHP
PHP的Laravel框架中使用消息队列queue及异步队列的方法
2016/03/21 PHP
JS判定是否原生方法
2013/07/22 Javascript
原生javascript图片自动或手动切换示例附演示源码
2013/09/04 Javascript
鼠标划过实现延迟加载并隐藏层的js代码
2013/10/11 Javascript
jquery.post用法关于type设置问题补充
2014/01/03 Javascript
让JavaScript和其它资源并发下载的方法
2014/10/16 Javascript
HTML5之WebSocket入门3 -通信模型socket.io
2015/08/21 Javascript
分享Javascript实用方法二
2015/12/13 Javascript
轻松搞定jQuery.noConflict()
2016/02/15 Javascript
js实现商品抛物线加入购物车特效
2020/11/18 Javascript
Bootstrap每天必学之警告框插件
2016/04/26 Javascript
JavaScript兼容浏览器FF/IE技巧
2016/08/14 Javascript
JS实现用户注册时获取短信验证码和倒计时功能
2016/10/27 Javascript
Angular和Vue双向数据绑定的实现原理(重点是vue的双向绑定)
2016/11/22 Javascript
js 发布订阅模式的实例讲解
2017/09/10 Javascript
vue脚手架搭建过程图解
2018/06/06 Javascript
iconfont的三种使用方式详解
2018/08/05 Javascript
对Vue- 动态元素属性及v-bind和v-model的区别详解
2018/08/27 Javascript
详解如何实现Element树形控件Tree在懒加载模式下的动态更新
2019/04/25 Javascript
[01:56]生活中的妖精之七夕特别档
2016/08/09 DOTA
web.py在SAE中的Session问题解决方法(使用mysql存储)
2015/06/24 Python
python中redis查看剩余过期时间及用正则通配符批量删除key的方法
2018/07/30 Python
在ubuntu16.04中将python3设置为默认的命令写法
2018/10/31 Python
Python语法之精妙的十个知识点(装B语法)
2020/01/18 Python
构建高效的python requests长连接池详解
2020/05/02 Python
纯CSS3实现的阴影效果
2014/12/24 HTML / CSS
英国旅行箱包和行李箱购物网站:Travel Luggage & Cabin Bags
2019/08/26 全球购物
linux面试题参考答案(11)
2016/11/26 面试题
幼儿园庆六一活动方案
2014/03/06 职场文书
煤矿开采专业求职信
2014/07/08 职场文书
北京英文导游词
2015/02/12 职场文书
幼师自荐信范文
2015/03/06 职场文书
2016年“世界环境日”校园广播稿
2015/12/18 职场文书