python中的内置函数getattr()介绍及示例
在python的官方文档中:getattr()的解释如下:
1
2
3
|
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”是对对象属性的名称,则返回对应属性的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
'# -*- 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' ) |
这段代码执行的结果是:
1
2
3
4
5
6
7
8
9
10
|
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.我需要在一个类中动态添加其它类中有的方法:
1
2
3
4
5
6
7
|
#如果类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()) |
我们只需要:
1
2
3
4
5
|
a = A() b = B() a.addnewattributesfromotherclass(b) |
这样a就可以调用B中的'非私有'方法啦。
python中的内置函数getattr()介绍及示例的更多相关文章
- python中的内置函数getattr()
在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the named attribu ...
- python中一些内置函数实例
lambda表达式 简单函数可用lambda表达式 1. def f1() return(123) r1=f1() print() 2. f2=lambda:123 r2=f2() print() 以 ...
- python中的内置函数(一)
内置函数:内置函数就是python提供的,可以拿来直接用的函数 作用域相关 locals():返回当前作用域中的名字globals():返回全局作用域中的内容 def func(): print('我 ...
- Python中的内置函数__init__()的理解
有点意思,本来我是学习java的.总所周知,java也有构造函数,而python在面向对象的概念中,也有构造函数.它就是 __init__(self) 方法. 其实类似于__init__()这种方法, ...
- python中的内置函数,递归,递归文件显示(二),二分法
1.部分内置函数 repr()显示出字符串的官方表示形式,返回一个对象的string形式 # repr 就是原封不动的输出, 引号和转义字符都不起作用 print(repr('大家好,\n \t我叫周 ...
- python中的内置函数(一), lambda, filter, map
https://www.processon.com/view/link/5c10da0ce4b099ae3e137bf6 1.内置函数 内置函数就是python中提供的,可以直接拿来用的函数,比如pr ...
- 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 ...
随机推荐
- C C++互相调用注意
注意:直接调用会找不到函数定义 1. C 调用 C++封装好后的函数: 在C++中有一个函数 int main_cpp(): 首先构建头文件, #ifndef CPP_FILE_H #define ...
- 深度学习环境搭建(ubuntu16.04+Titan Xp安装显卡驱动+Cuda9.0+cudnn+其他软件)
一.硬件环境 ubuntu 16.04LTS + windows10 双系统 NVIDIA TiTan XP 显卡(12G) 二.软件环境 搜狗输入法 下载地址 显卡驱动:LINUX X64 (AMD ...
- laravel文件上传
一.视图文件代码 <td> <input type="file" name="brand_logo" id="logo" ...
- aop(权限控制)
创建sysContext (管理请求) package com.tp.soft.common.util; import javax.servlet.http.HttpServletRequest; i ...
- Hybrid App 开发模式
开发移动App主要有三种模式:Native. Hybrid 和 Web App. 需要注意的一点是在选择开发模式的时候,要根据你的项目类型(图片类?视频类?新闻类?等),产品业务和人员技术储备等做权衡 ...
- 2019金融科技风往哪儿吹?蚂蚁金服联合20余家金融机构预测新年热点:5G、区块链上榜
2019年,金融科技的风向标在哪里?哪些板块成新宠,哪些科技成潮流? 1月4日,蚂蚁金服ATEC城市峰会在上海举行.大会上,蚂蚁金服与20余家金融机构一起预测了2019年金融科技的发展. “未来金融会 ...
- C++_day8_ 多重继承、钻石继承和虚继承
1.继承的复习 1.1 类型转换 编译器认为访问范围缩小是安全的. 1.2 子类的构造与析构 子类中对基类构造函数初始化只能写在初始化表里,不能写在函数体中. 阻断继承. 1.3 子类的拷贝构造与拷贝 ...
- js中的继承总结全( 含new 原理过程 )
1. 借用 new 构造函数继承 原理: 利用 new 的原理, 通过apply,call , bind 改变 this , 只能实现部分方法的继承: MDN对new的描述: new 运算符创建一个 ...
- Oracle 并发创建索引
建索引时,我们为了建索引快,会加上并行,加上并行之后,此列索引就会是并行了.访问有并行度的索引时,CBO可能可能会考虑并行执行,这可能会引发一些问题,如在服务器资源紧张的时候用并行会引起更加严重的争用 ...
- C# WebClient实现文件上传
一.同步上传 文章 https://www.cnblogs.com/duanjt/p/6420172.html 里面有提到服务端通过WebApi如何实现文件上传,这里就只说客户端使用WebClient ...