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 lucaslucasattribute1 is indirectly called by fun()<type 'instancemethod'>attribute1 called and crown is passed in as a parameterattrribute1 is directly calledattribute1 called and tomato is passed in as a parameterProcess 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 ...
随机推荐
- 部署springboot项目时 打包成jar时包中html,js,css文件缺失
问题 打包出来的jar包里面没有html,js,css文件 解决方案 在pom.xml文件下的build选项中的src/main/resources的目录下 添加配置 <build> &l ...
- 论文笔记:Siamese Cascaded Region Proposal Networks for Real-Time Visual Tracking
Siamese Cascaded Region Proposal Networks for Real-Time Visual Tracking 2019-03-20 16:45:23 Paper:ht ...
- 洛谷 P3381 【【模板】最小费用最大流】
题目描述 如题,给出一个网络图,以及其源点和汇点,每条边已知其最大流量和单位流量费用,求出其网络最大流和在最大流情况下的最小费用. 输入 第一行包含四个正整数N.M.S.T,分别表示点的个数.有向边的 ...
- CentOS7攻克日记(一) —— 安装ISO
因为工作需要,开发环境需要装在centos7上面,这对用惯了ubuntu 这种Debian系的我,此刻只想说一句MMP 自从刚开始弄到现在VM里面已经躺了一堆的Centos7的尸体了,这次从头初始 ...
- 2018年底,IOS面试题的复习之OC的反射机制
明天要去面试一个公司,今天复习下IOS题目吧 1.说一下OC的反射机制 答:OC的反射机制类似于JAVA的反射机制,这种动态反射机制可以让OC语言更加灵活.这句话是对反射机制的初步认识,具体表现在哪里 ...
- swift 有道 翻译文档(2 条件语句 循环语句)
控制流使用if和switch来创建条件语句,使用for-in.while和repeat-while来创建循环.条件或循环变量的括号是可选的.身体周围需要支撑. let individualScores ...
- 记一次IIS发布网站导致系统时常跳入登录页面的问题解决
服务器:winserver2012R2 iis 发布网站后,正常浏览网页,时常跳到登录页面,第一反应session过期,因为登录信息都存在session,但session 都是默认配置过期时间为20分 ...
- poj2528 Mayor's posters (线段树+离散化)
恩,这区间范围挺大的,需要离散化.如果TLE,还需要优化一下常数. AC代码 #include <stdio.h> #include <string.h> #include & ...
- ArcGIS JS API4 With VueJS集成开发
1.USING VUEJS WITH ARCGIS API FOR JAVASCRIPT,集成VUE到ArcGIS JS开发中. 2.ARCGIS API 4 FOR JS WITH VUE-CLI ...
- selenium+Headless Chrome实现不弹出浏览器自动化登录
目前由于phantomjs已经不维护了,而新版的Chrome(59+)推出了Headless模式,对爬虫来说尤其是定时任务的爬虫截屏之类的是一大好事. 不过按照网络上的一些方法来写的话,会报下面的错误 ...