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 ...
随机推荐
- iOS 使用interface builder 创建太复杂的constrains时容易产生crash
今天写程序,遇到了crash,在界面初始化时不会有,想切换到别的tab页就报错了.主要内容如下: Cannot find an outgoing row head for incoming head ...
- Java for LeetCode 030 Substring with Concatenation of All Words【HARD】
You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...
- BestCoder12 1001.So easy(hdu 5058) 解题报告
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5058 (格式有点问题,为了方便阅读---整个复制下来吧) 题目意思:给出两个长度都为 n 的集合你,问 ...
- LightOJ 1247 Matrix Game (尼姆博弈)
A - Matrix Game Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu Submi ...
- 配置redis外网可访问
redis采用的安全策略,默认会只准许本地访问 通过简单配置,完成允许外网访问 [root@cache01 conf]# egrep "(^bind|#bind|# bind)" ...
- HTML5中的DOMContentLoaded 和 touchmove
Html5的出现确实解决了一部分页面交互的问题,同时它的一些特性还是没能被我们掌握,今天主要聊聊Html5中的DomcontenLoaded和touchmove事件的属性和使用: DomcontenL ...
- UML从需求到实现----用例
关于用例图的概念相信不用我去说了 .能看到这篇文章的都是知道用例图概念的人. UML 中最重要的是什么图呢 ?毫无疑问应该是用例图 ,用例是后期时序图 和实际开发的重要依据. 说明一下用例图是怎么产生 ...
- mac os下获得root权限
警告:对系统不了解的请慎用 操作步骤:1.打开实用工具->终端2.键入sudo passwd root 然后提示你输入当前登录用户密码,通过以后,提示你输入两遍root的密码.这样你就设置好ro ...
- [原]DbHelper-SQL数据库访问助手
using System; using System.Data; using System.Data.SqlClient; namespace Whir.Software.Framework.Ulti ...
- python网页爬虫
1. 静态页面爬取 这类最简单啦,右键->查看页面源码时,想下载的信息都能够显示在这里,这时只需要直接down页面源码,代码如下: # Simple open web import urllib ...