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实现的希尔排序算法实例
Jul 01 Python
python爬虫使用cookie登录详解
Dec 27 Python
Python读csv文件去掉一列后再写入新的文件实例
Dec 28 Python
python实现聚类算法原理
Feb 12 Python
Python爬虫包BeautifulSoup实例(三)
Jun 17 Python
python重试装饰器的简单实现方法
Jan 31 Python
python覆盖写入,追加写入的实例
Jun 26 Python
详解字符串在Python内部是如何省内存的
Feb 03 Python
pyCharm 实现关闭代码检查
Jun 09 Python
python实现逻辑回归的示例
Oct 09 Python
python3 字符串str和bytes相互转换
Mar 23 Python
Python中的socket网络模块介绍
Jul 23 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 mssql 数据库分页SQL语句
2008/12/16 PHP
php 调用远程url的六种方法小结
2009/11/02 PHP
CI(CodeIgniter)模型用法实例分析
2016/01/20 PHP
php 7新特性之类型申明详解
2017/06/06 PHP
php微信公众号开发之关键词回复
2018/10/20 PHP
发两个小东西,ASP/PHP 学习工具。 用JavaScript写的
2007/04/12 Javascript
List all the Databases on a SQL Server
2007/06/21 Javascript
javascript (用setTimeout而非setInterval)
2011/12/28 Javascript
JS对象与JSON格式数据相互转换
2012/02/20 Javascript
IE6下javasc#ipt:void(0) 无效的解决方法
2013/12/23 Javascript
JavaSript中变量的作用域闭包的深入理解
2014/05/12 Javascript
JavaScript中匿名、命名函数的性能测试
2014/09/04 Javascript
JavaScript弹出新窗口并控制窗口移动到指定位置的方法
2015/04/06 Javascript
Bootstrap CSS组件之按钮下拉菜单
2016/12/17 Javascript
BootStrap实现轮播图效果(收藏)
2016/12/30 Javascript
select下拉框插件jquery.editable-select详解
2017/01/22 Javascript
5分钟打造简易高效的webpack常用配置
2017/07/04 Javascript
详解微信小程序的 request 封装示例
2018/08/21 Javascript
Vue+Koa2+mongoose写一个像素绘板的实现方法
2019/09/10 Javascript
JS实现小星星特效
2019/12/24 Javascript
微信小程序以7天为周期连续签到7天功能效果的示例代码
2020/08/20 Javascript
Python使用filetype精确判断文件类型
2017/07/02 Python
python自动发送测试报告邮件功能的实现
2019/01/22 Python
python中报错&quot;json.decoder.JSONDecodeError: Expecting value:&quot;的解决
2019/04/29 Python
python的命名规则知识点总结
2019/10/04 Python
PyCharm使用之配置SSH Interpreter的方法步骤
2019/12/26 Python
Pytorch evaluation每次运行结果不同的解决
2020/01/02 Python
详解Python中的分支和循环结构
2020/02/11 Python
numpy库reshape用法详解
2020/04/19 Python
捷克体育用品购物网站:D-sport
2017/12/28 全球购物
Tod’s英国官方网站:意大利奢华手工制作手袋和鞋履
2019/03/15 全球购物
奥地利票务门户网站:oeticket.com
2019/12/31 全球购物
金智子午JAVA面试题
2015/09/04 面试题
自动化职业生涯规划书范文
2014/01/03 职场文书
银行反洗钱宣传活动总结
2015/05/08 职场文书
2019个人工作计划书的格式及范文!
2019/07/04 职场文书