python中的内置函数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())
我们只需要:
a = A()
b = B()
a.addnewattributesfromotherclass(b)
这样a就可以调用B中的'非私有'方法啦。
python中的内置函数getattr()的更多相关文章
- python中的内置函数getattr()介绍及示例
在python的官方文档中:getattr()的解释如下: ? 1 2 3 getattr(object, name[, default]) Return the value of the nam ...
- python中一些内置函数实例
lambda表达式 简单函数可用lambda表达式 1. def f1() return(123) r1=f1() print() 2. f2=lambda:123 r2=f2() print() 以 ...
- python中的内置函数,递归,递归文件显示(二),二分法
1.部分内置函数 repr()显示出字符串的官方表示形式,返回一个对象的string形式 # repr 就是原封不动的输出, 引号和转义字符都不起作用 print(repr('大家好,\n \t我叫周 ...
- python中的内置函数(一), lambda, filter, map
https://www.processon.com/view/link/5c10da0ce4b099ae3e137bf6 1.内置函数 内置函数就是python中提供的,可以直接拿来用的函数,比如pr ...
- python中的内置函数(一)
内置函数:内置函数就是python提供的,可以拿来直接用的函数 作用域相关 locals():返回当前作用域中的名字globals():返回全局作用域中的内容 def func(): print('我 ...
- python中的内置函数(2)
一.lambda匿名函数定义:为了解决一些简单的需求而设计的一句话函数例子:计算n的n次方 def func(n):#正常的写法 return n**2 f=lambda n:n**2 这里的lamb ...
- 2018.8.14 python中的内置函数(68个)
主要内容: python中68个内置函数的功能及使用方法
- python学习之【第十篇】:Python中的内置函数
1.前言 内置函数,就是Python内部预先定义好的函数,可以直接使用,Python中内置函数有以下这么多个: 2.map() 描述: map() 会根据提供的函数对指定序列做映射.第一个参数 fun ...
- Python中max()内置函数使用(list)
在学习完列表和元组的基础知识后,做到一个题: 求出列表中频次出现最多的元素. 学习到了python内置函数max的用法 其参数key的用法 匿名函数lamda的用法 python内置函数max() m ...
随机推荐
- 纪录JVM内存模型内容
声明:本内容是博主在牛客网上看到的网友发表的答案,因为感觉总结的比较好,所以摘抄过来供大家学习. 内容: 大多数 JVM 将内存区域划分为 Method Area(Non-Heap)(方法区) ,He ...
- Informatica Powercenter学习笔记
LOOKUP TRANSFORMATION的使用点评: LOOKUP基本用法不熟的话请参考下附属信息. 用法感受: 1 LOOKUP的作用跟我们以前在EXCEL的函数功能类似,就是隔表取值.优点就是用 ...
- HTTP 协议中的 Content-Encoding 和 Transfer-Encoding(内容编码和传输编码)
转自:http://network.51cto.com/art/201509/491335.htm Transfer-Encoding,是一个 HTTP 头部字段,字面意思是「传输编码」.实际上,HT ...
- 测试mysql的sql语句预编译效果
玩Oracle的都比较关注shared pool,特别是library cache,在使用了绑定变量(预编译sql)之后确实能得到很大的性能提升.现在在转Mysql之后特别是innodb很多东西都还能 ...
- 【原创】大众点评监控平台cat的性能分析
由于工作的原因,或者说我们之前内部监控设计和实现有点不满足现有的研发需求,所以调研了一下大众点评开源出来的cat这一套监控系统. 今天我们就来实验一把,cat的客户端埋点在我们的程序流程中上报数据到c ...
- cocos2d-x之物理引擎初试
发现问题:监听代码部分不能在onEnter()段书写 bool HelloWorld::init() { if ( !Layer::init() ) { return false; } visible ...
- android适配器及监听点击和滚动在ListView中的使用
package com.example.demon08; import java.util.ArrayList;import java.util.HashMap;import java.util.Li ...
- Github学习之路-初出茅庐,接触Github,了解Github
一.了解GitHub 作为一个在线协作网站,GitHub允许程序员们分享和协力于开源项目的工作. GitHub不仅是一个分享开源创作并与其它程序员合作的好地方,你也可以从GitHub上收到自己作品的 ...
- nyoj 237 游戏高手的烦恼 二分匹配--最小点覆盖
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=237 二分匹配--最小点覆盖模板题 Tips:用邻接矩阵超时,用数组模拟邻接表WA,暂时只 ...
- 关于点击ztree的节点将页面生成到easyui的新增选项卡(easyui-tabs)时,总是在浏览器中生成一个新的页面的问题
最近的项目中用到了easyui,还有ztree菜单.在这里将我遇到的一些问题写出来算是做个笔记吧. 这是我头一次在博客园里分享代码,我的处女作,写的不好的地方还望各位见谅! 由于很久没有写过前台的东西 ...