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 基于lvm快照的备份

    1.查看磁盘数 ls /dev/ | grep sd 2.快照备份 pvcreate /dev/sdb #制作成物理卷vgcreate testvg /dev/sdblvcreate -L200M - ...

  2. 用php计算行列式

    因为有课程设计要计算多元一次方程组,所以想编个程序实现,多元一次方程组的计算最系统的方法就是利用克拉默法则求解方程组,所以只需要编写一个类或者方法求出多元一次方程组系数行列式的值和和其他几个行列式,如 ...

  3. codeforces C. Arithmetic Progression 解题报告

    题目链接:http://codeforces.com/problemset/problem/382/C 题目意思:给定一个序列,问是否可以通过只插入一个数来使得整个序列成为等差数列,求出总共有多少可能 ...

  4. mybatis整合spring 之 基于接口映射的多对一关系

    转载自:http://my.oschina.net/huangcongmin12/blog/83731 mybatis整合spring 之  基于接口映射的多对一关系. 项目用到俩个表,即studen ...

  5. excel数据导入SQLite数据库

    参考:http://blog.baisi.net/?110653/viewspace-6725 1.excel表中最上面一行的字段名留着,留着以后导入的时候对应. 2.保存成csv格式,在选择文件类型 ...

  6. 铺地毯(luogu 1003)

    题目描述 为了准备一个独特的颁奖典礼,组织者在会场的一片矩形区域(可看做是平面直角坐标系的第一象限)铺上一些矩形地毯.一共有 n 张地毯,编号从 1 到n .现在将这些地毯按照编号从小到大的顺序平行于 ...

  7. svn上想回滚代码怎么办?——svn merge 命令

    小博客断更了很久,最近想接着尝试建立写作的习惯,把自己工作生活遇到的有用知识沉淀下来.尽管微信公共账号比较火,但个人觉得这种不能用搜索引擎检索的东西完全就是历史的倒退,就像 RSS 这种提高信息传播效 ...

  8. hdu 4833 离散化+dp ****

    先离散化,然后逆着dp,求出每个点能取到的最大利益,然后看有没有钱,有钱就投 想法好复杂 #include <stdio.h> #include <string.h> #inc ...

  9. dp核心问题研究-从入门到放弃

    首先从数字三角形开始 这个题的特点是..本身遍历次序就是个树型的 每次的决策都已经给定,左下或者右下 并且当我们纠结于是往左下走还是往右下走的时候,每次根据当前的情况贪心都为时尚早,因为后面的数据可以 ...

  10. Loadrunner模拟JSON接口请求进行测试

    Loadrunner模拟JSON接口请求进行测试     一.loadrunner脚本创建 1.Insert - New step -选择Custom Request -  web_custom_re ...