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(2881064151))
复制代码
我们只需要:
a = A()
b = B()
a.addnewattributesfromotherclass(b)
getattr的作用是什么呢的更多相关文章
- python中的内置函数getattr()
在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the named attribu ...
- python中的内置函数getattr()介绍及示例
在python的官方文档中:getattr()的解释如下: ? 1 2 3 getattr(object, name[, default]) Return the value of the nam ...
- python hasattr()函数,getattr()函数, setattr()函数
1. hasattr(object, ‘属性名 or 方法名') 判断一个对象里面是否有某个属性或者某个方法,返回布尔值,有某个属性或者方法返回True, 否则返回False 2. getattr() ...
- python中的反射
在绝大多数语言中,都有反射机制的存在.从作用上来讲,反射是为了增加程序的动态描述能力.通俗一些,就是可以让用户参与代码执行的决定权.在程序编写的时候,我们会写很多类,类中又有自己的函数,对象等等.这些 ...
- 《Dive into Python》Chapter 4 笔记
自省:Python中万物皆对象,自省是指代码可以查看内存中以对象形式存在的其它模块和函数,获取它们的信息,并对它们进行操作.用这种方法,可以定义没有名称的函数,不按函数声明的参数顺序调用函数,甚至引用 ...
- python自省函数getattr的用法
getattr是python里的一个内建函数 getattr()这个方法最主要的作用是实现反射机制.也就是说可以通过字符串获取方法实例.这样,你就可以把一个类可能要调用的方法放在配置文件里,在需要的时 ...
- python 内建函数setattr() getattr()
python 内建函数setattr() getattr() setattr(object,name,value): 作用:设置object的名称为name(type:string)的属性的属性值为v ...
- python中getattr函数 hasattr函数
hasattr(object, name)作用:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的).示例: > ...
- python中的getattr函数
getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') i ...
随机推荐
- Java for LeetCode 060 Permutation Sequence
The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the p ...
- Java for LeetCode 047 Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations ...
- sysctl命令详解
个人一般sysctl -p 或sysctl -a比较多使用 sysctl配置与显示在/proc/sys目录中的内核参数.可以用sysctl来设置或重新设置联网功能,如IP转发.IP碎片去除以及源路由检 ...
- vector容器+iterator迭代器
关于vector容器的详细描述,可参考:http://www.jb51.net/article/41648.htm 关于iterator迭代器的描述,可参考http://www.cppblog.c ...
- Diablo3
1.装备 主手:元素弓 副手:精细箭袋 头: 胸:燃火外套 手:娜塔亚的手感 护腕:稳击护腕 戒指:罗盘玫瑰+布尔凯索的婚戒 颈部:旅者之誓 腰:科雷姆的强力腰带(速度加25%) 腿:深渊挖掘裤 脚: ...
- linux架构图
/ 根目录 │ ├boot/ 启动文件.所有与系统启动有关的文件都保存在这里 │ └grub/ Grub引导器相关的文件 │ ├dev/ 设备文件 ├proc/ 内核与进程镜像 │ ├mnt/ 临时挂 ...
- Feed系统架构资料收集
完全用nosql轻松打造千万级数据量的微博系统 微博feed系统的push和pull模式和时间分区拉模式架构探讨 关于如何构建一个微博型广播 关于如何构建一个微博型广播2 用 mongodb 储存多态 ...
- VBScript [ 译 ]
VBScript ( Visual Basic Scripting Edition) 使用COM 来和宿主环境交互.从Microsoft Windows 98 开始的所有的微软桌面操作系统的relea ...
- matlab练习程序(最小包围矩形)
又是计算几何,我感觉最近对计算几何上瘾了. 当然,工作上也会用一些,不过工作上一般直接调用boost的geometry库. 上次写过最小包围圆,这次是最小包围矩形,要比最小包围圆复杂些. 最小包围矩形 ...
- LoadRunner字符串与参数的操作及转换技巧
刚开始学LR时,经常搞不清楚变量和参数的区别与用法,最近在一次脚本编写中,整理出来的一些小技巧,与大家一起分享. //字符串复制 strcpy(str,"Hello ") ; // ...