python中的内置函数getattr()介绍及示例

 更新时间:2014年07月20日 14:56:03   投稿:hebedich  
其实getattr()这个方法最主要的作用是实现反射机制。也就是说可以通过字符串获取方法实例。这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时候动态加载。

在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常见基础面试题及答案

    Python是目前编程领域最受欢迎的语言,Python可用于许多领域,Web应用程序开发,自动化,数学建模,大数据应用程序等等,这篇文章主要给大家介绍了关于Python常见基础面试题及答案的相关资料,需要的朋友可以参考下
    2021-09-09
  • Python 获得13位unix时间戳的方法

    Python 获得13位unix时间戳的方法

    本篇文章主要介绍了Python 获得13位unix时间戳的方法,非常具有实用价值,需要的朋友可以参考下
    2017-10-10
  • 在Apache服务器上同时运行多个Django程序的方法

    在Apache服务器上同时运行多个Django程序的方法

    这篇文章主要介绍了在Apache服务器上同时运行多个Django程序的方法,Django是Python各色高人气web框架中最为著名的一个,需要的朋友可以参考下
    2015-07-07
  • python接口自动化使用requests库发送http请求

    python接口自动化使用requests库发送http请求

    这篇文章主要介绍了python接口自动化使用requests库发送http请求,HTTP协议 ,一个基于TCP/IP通信协议来传递数据,包括html文件、图像、结果等,即是一个客户端和服务器端请求和应答的标准
    2022-08-08
  • 基于Python socket实现简易网络聊天室

    基于Python socket实现简易网络聊天室

    本文主要介绍了基于Python socket实现简易网络聊天室,本文将通过pyqt5作为桌面应用框架,socket作为网络编程的框架,从而实现包括客户端和服务端的网络聊天室的GUI应用,需要的可以参考一下
    2022-07-07
  • 解决python通过cx_Oracle模块连接Oracle乱码的问题

    解决python通过cx_Oracle模块连接Oracle乱码的问题

    今天小编就为大家分享一篇解决python通过cx_Oracle模块连接Oracle乱码的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • OpenCV-Python实现油画效果的实例

    OpenCV-Python实现油画效果的实例

    OpenCV是功能强大的计算机视觉库,本文主要使用OpenCV来实现图片的油画效果,需要的朋友们下面随着小编来一起学习学习吧
    2021-06-06
  • Python经典五人分鱼实例讲解

    Python经典五人分鱼实例讲解

    在本篇文章里小编给大家分享的是一篇关于Python 五人分鱼的经典小游戏实例内容,有兴趣的朋友们可以学习下。
    2021-01-01
  • Python的条件语句与运算符优先级详解

    Python的条件语句与运算符优先级详解

    这篇文章主要介绍了Python的条件语句与运算符优先级,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-10-10
  • Pygame的程序开始示例代码

    Pygame的程序开始示例代码

    这篇文章主要介绍了Pygame的程序开始的示例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05

最新评论