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(2881064151))

复制代码

我们只需要:

a = A()

b = B()

a.addnewattributesfromotherclass(b)

getattr的作用是什么呢的更多相关文章

  1. python中的内置函数getattr()

    在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the named attribu ...

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

    在python的官方文档中:getattr()的解释如下: ? 1 2 3 getattr(object, name[, default])   Return the value of the nam ...

  3. python hasattr()函数,getattr()函数, setattr()函数

    1. hasattr(object, ‘属性名 or 方法名') 判断一个对象里面是否有某个属性或者某个方法,返回布尔值,有某个属性或者方法返回True, 否则返回False 2. getattr() ...

  4. python中的反射

    在绝大多数语言中,都有反射机制的存在.从作用上来讲,反射是为了增加程序的动态描述能力.通俗一些,就是可以让用户参与代码执行的决定权.在程序编写的时候,我们会写很多类,类中又有自己的函数,对象等等.这些 ...

  5. 《Dive into Python》Chapter 4 笔记

    自省:Python中万物皆对象,自省是指代码可以查看内存中以对象形式存在的其它模块和函数,获取它们的信息,并对它们进行操作.用这种方法,可以定义没有名称的函数,不按函数声明的参数顺序调用函数,甚至引用 ...

  6. python自省函数getattr的用法

    getattr是python里的一个内建函数 getattr()这个方法最主要的作用是实现反射机制.也就是说可以通过字符串获取方法实例.这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时 ...

  7. python 内建函数setattr() getattr()

    python 内建函数setattr() getattr() setattr(object,name,value): 作用:设置object的名称为name(type:string)的属性的属性值为v ...

  8. python中getattr函数 hasattr函数

    hasattr(object, name)作用:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的).示例: > ...

  9. python中的getattr函数

    getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') i ...

随机推荐

  1. MySQL入门书籍和方法分享

    本文罗列了一些适用于MySQL及运维入门和进阶使用的书籍. 背景:各大论坛上总是有很多同学咨询想学习数据库,或者是为入行DBA做些准备.几年来作为一个MySQL DBA的成长过程有一些积累和感悟,特此 ...

  2. mysql源码:关于innodb中两次写的探索

    两次写可以说是在Innodb中很独特的一个功能点,而关于它的说明或者解释非常少,至于它存在的原因更没有多少文章来说,所以我打算专门对它做一次说明. 首先说明一下为什么会有两次写这个东西:因为innod ...

  3. 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays

    There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...

  4. Java for LeetCode 038 Count and Say

    The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221 ...

  5. 《Effective Java》笔记 使类和成员的可访问性最小化

    类和接口 第13条 使类和成员的可访问性最小化 1.设计良好的模块会隐藏所有的实现细节,把它的API与实现清晰的隔离开来,模块之间只通过它们的API进行通信,一个模块不需要知道其他模块的内部工作情况: ...

  6. ***Linux文件夹文件创建、删除、改名

    Linux删除文件夹命令 linux删除目录很简单,很多人还是习惯用rmdir,不过一旦目录非空,就陷入深深的苦恼之中,现在使用rm -rf命令即可.直接rm就可以了,不过要加两个参数-rf 即:rm ...

  7. Duilib非官方更新贴~

    GitHub: https://github.com/movsb/duilib.git 2014-07-20: [76a04d1]    [BugFix] 修复无法解析类似<Control/&g ...

  8. [原]DbHelper-SQL数据库访问助手

    using System; using System.Data; using System.Data.SqlClient; namespace Whir.Software.Framework.Ulti ...

  9. Syncfusion的社区许可及免费电子书和白皮书

    今晚由于要忙于其他事情,就简单的给大家推荐一个第三方组件库.特别注明:这是我义务为这家公司打广告.毕竟我从他们公司收获了很多知识. Syncfusion是一家微软生态下的第三方组件/控件供应商,算是后 ...

  10. Android DrawerLayout 高仿QQ5.2双向侧滑菜单

    1.概述 之前写了一个Android 高仿 QQ5.0 侧滑菜单效果 自定义控件来袭 ,恰逢QQ5.2又加了一个右侧菜单,刚好看了下DrawerLayout,一方面官方的东西,我都比较感兴趣:另一方面 ...