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. php抽象类的简单应用

    抽象类也是面向对象中的重要概念,和接口.继承的概念重要性相当,在面向对象的开发中,所有的对象都是通过类来描述的,但是反过来,并不是所有类都是用来描绘对象的,广义上讲如果一个类中没有足够信息来描述一个具 ...

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

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

  3. C语言字符串处理

    一. C语言中,为什么字符串可以赋值给字符指针变量 char *p,a='5';p=&a;                     //显然是正确的,p="abcd";   ...

  4. android 中如何分析内存泄漏

    转载:http://blog.csdn.net/fulinwsuafcie/article/details/8363218 前提条件: 1,电脑安装了java 运行环境 2,手机端开启了 USB 调试 ...

  5. Java中ArrayList的自我实现

    对于ArrayList相比大家都很熟悉,它是java中最常用的集合之一.下面就给出它的自我实现的java代码. 需要说明的一点是,它是基于数组创建的.所以它在内存中是顺序存储,对于查找十分的方便. p ...

  6. linux下常见的文件夹含义

    1./bin :获得最小的系统可操作性所需要的命令2./boot :内核和加载内核所需的文件3./dev :终端.磁盘.调制解调器等的设备项4./etc :关键的启动文件和配置文件5./home :用 ...

  7. hibernate的sqlQuery自动封装

    1.Query query = session.createSQLQuery("SQL").addEntity(Tree.class); //返回对象   List  list = ...

  8. C#控制管理VisualSVN Server 分类: C# 2014-05-29 15:51 796人阅读 评论(0) 收藏

    VisualSVN Server可以用WMI接口管理(Windows Management Instrumentation). VisualSVN Server安装的计算机中,位于%VISUALSVN ...

  9. Sqlite实现默认时间为当前时间列的方法(转)

    原文地址: http://blog.csdn.net/derryzhang/article/details/5033209 在SQL Server中,创建表格的时候,对于时间列有时候我们可以根据需要指 ...

  10. C++Premer Plus学习(五)——函数探幽

    一.内联函数 1.优点: 内联函数就是比较省资源,然后一般就是将简短,使用频率高的函数作为内联函数会比较合适. 2.一个demo #include "stdafx.h" #incl ...