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. Android 转载一篇.9图片详解文章

    感谢作者,原文链接为 http://blog.csdn.net/ouyang_peng/article/details/9242889

  2. windows下安装Appserv等php套件之后无法进入数据库管理的问题

    在win7下安装Wamp或者Appserv后无法进入数据库管理,但是php.Apache运行全都没问题,mysql可以在命令行中管理,但是就是无法打开phpmyadmin数据库管理,点击后浏览器就显示 ...

  3. 【读书笔记】读《JavaScript设计模式》之装饰者模式

    一.定义 装饰者模式可用来透明地把对象包装在具有同样接口的另一个对象之中.这样一来,你可以给一个方法添加一些行为,然后将方法调用传递给原始对象.相对于创建子类来说,使用装饰者对象是一种更灵活的选择(装 ...

  4. Android之UI控件

    本文主要包括以下内容 Spinner的使用 Gallery的使用 Spinner的使用 Spinner的实现过程是 1. 在xml文件中定义Spinner的控件 2. 在activity中获取Spin ...

  5. Shell脚本入门与应用

    编写第一个shell脚本 如同其他语言一样,通过我们使用任意一种文字编辑器,比如 nedit.kedit.emacs.vi 等来编写我们的 shell 程序.程序必须以下面的行开始(必须方在文件的第一 ...

  6. oracle11g客户端 安装图解

    软件位置:我的网盘 -- oracle空间 -- oracle工具 -- win64_11gR2_database_clint(客户端) -- 压缩软件包 先将下载下来的ZIP文件解压,并运行setu ...

  7. Html页面插入flash代码

    转自:http://www.educity.cn/jianzhan/402117.html 转自:http://www.cnblogs.com/yxc_fj/articles/1390621.html ...

  8. Ubuntu各版本下载地址

    Ubuntu各版本下载地址:     http://old-releases.ubuntu.com/releases/

  9. Android Inflate

    inflate就相当于将一个xml中定义的布局找出来. 三种方式可以生成LayoutInflater: LayoutInflaterinflater=LayoutInflater.from(this) ...

  10. Java正则表达式, 提取双引号中间的部分

    String str="this is \"Tom\" and \"Eric\", this is \"Bruce lee\", ...