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 字典(Dictionary)操作详解
Mar 11 Python
python实现telnet客户端的方法
Apr 15 Python
ubuntu系统下 python链接mysql数据库的方法
Jan 09 Python
python读写json文件的简单实现
Apr 11 Python
python中的迭代和可迭代对象代码示例
Dec 27 Python
对pandas处理json数据的方法详解
Feb 08 Python
python实现爬取百度图片的方法示例
Jul 06 Python
解析python 类方法、对象方法、静态方法
Aug 15 Python
Python虚拟环境的创建和使用详解
Sep 07 Python
pytorch 移动端部署之helloworld的使用
Oct 30 Python
python中判断数字是否为质数的实例讲解
Dec 06 Python
教你怎么用python实现字符串转日期
May 24 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程序中使用Rust扩展的方法
2015/07/03 PHP
Yii2.0使用阿里云OSS的SDK上传图片、下载、删除图片示例
2017/09/20 PHP
Laravel Intervention/image图片处理扩展包的安装、使用与可能遇到的坑详解
2017/11/14 PHP
PHP笛卡尔积实现原理及代码实例
2020/12/09 PHP
科讯商业版中用到的ajax空间与分页函数
2007/09/02 Javascript
通过JS 获取Mouse Position(鼠标坐标)的代码
2009/09/21 Javascript
js页面滚动时层智能浮动定位实现(jQuery/MooTools)
2011/08/23 Javascript
jquery 检测元素是否存在的实例代码
2013/11/19 Javascript
什么是cookie?js手动创建和存储cookie
2014/05/27 Javascript
js与jquery实时监听输入框值的oninput与onpropertychange方法
2015/02/05 Javascript
删除javascript所创建子节点的方法
2015/05/21 Javascript
tuzhu_req.js 实现仿百度图片首页效果
2015/08/11 Javascript
js判断手机号运营商的方法
2015/10/23 Javascript
JavaScript中实现键值对应的字典与哈希表结构的示例
2016/06/12 Javascript
jQuery获取file控件中图片的宽高与大小
2016/08/04 Javascript
动态生成的DOM不会触发onclick事件的原因及解决方法
2016/08/06 Javascript
微信JS接口大全
2016/08/25 Javascript
AngularJS开发教程之控制器之间的通信方法分析
2016/12/25 Javascript
jQuery实现的省市联动菜单功能示例【测试可用】
2017/01/13 Javascript
微信小程序 UI与容器组件总结
2017/02/21 Javascript
分分钟玩转Vue.js组件(二)
2017/03/01 Javascript
jQuery 实现图片的依次加载图片功能
2017/07/06 jQuery
JS+jQuery实现注册信息的验证功能
2017/09/26 jQuery
javaScript实现复选框全选反选事件详解
2020/11/20 Javascript
Angular resolve基础用法详解
2018/10/03 Javascript
wxpython中自定义事件的实现与使用方法分析
2016/07/21 Python
Python图片的横坐标汉字实例
2019/12/04 Python
Python使用gluon/mxnet模块实现的mnist手写数字识别功能完整示例
2019/12/18 Python
使用python实现哈希表、字典、集合操作
2019/12/22 Python
关于django python manage.py startapp 应用名出错异常原因解析
2020/12/15 Python
纽约著名的服装辅料来源:M&J Trimming
2017/07/26 全球购物
Unix控制后台进程都有哪些进程
2016/09/22 面试题
会计毕业生自我鉴定
2013/11/04 职场文书
大学生村官心得体会范文
2014/01/04 职场文书
推普周活动总结
2014/08/28 职场文书
中学感恩教育活动总结
2015/05/05 职场文书