python中的内置函数getattr()介绍及示例
作者:hebedich 发布时间:2023-01-15 19:16:46
标签: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中的'非私有'方法啦。
0
投稿
猜你喜欢
- 分析使用CrawlSpider结合LinkExtractor和Rule爬取网页信息LinkExtractor用于定义链接提取规则,一般使用a
- 本文实例讲述了Python实现telnet服务器的方法。分享给大家供大家参考。具体实现方法如下:import threading class
- 本文实例为大家分享了python实现排序算法的具体代码,供大家参考,具体内容如下一、冒泡排序def bububle_sort(alist):
- 在安装完数据库后,由于自己不小心直接关闭了安装窗口,或者长时间没有使用root用户登录系统,导致忘记了root密码,这时就需要重置MySQL
- 与其他主流语言如 Javascript、Java 和 Python 相比,Golang 的错误处理方式可能和这些你熟悉的语言有所不同。所以才
- 以下的文章主要介绍的是SQL Serve数据库到DB2连接服务器的实现过程,我们大家都知道不同数据库平台的互连,一般对其称之为数据库的异构服
- 虽然你可以使用一个类似的技术以拒绝过大的文件(通过检查$uploadedfile_size变量),但是通常这不是一个好主意。在得到这个变量之
- 效果图:搜索分类2种情况,一般的是当用户输入完,点击确定的按钮在向后发送请求,还有一种就是的我一边输入,一边向后台发送请求,但是会产生一个性
- 一、模板图像处理(1)灰度图、二值图转化template = cv2.imread('C:/Users/bwy/Desktop/nu
- 一:安装MySQL-python驱动 pip install mysql二:连接到MySQL服务器的test数据库#!/usr/
- 1、字符串拼接通过+运算符现有字符串码农飞哥好,,要求将字符串码农飞哥牛逼拼接到其后面,生成新的字符串码农飞哥好,码农飞哥牛逼举个例子:st
- 从windows操作系统本地读取csv文件报错data = pd.read_csv(path)Traceback (most recent
- 来炫耀一下,谁看得懂我写的加密算法写了一整天了,这个代码用于ajax提交,要求就是加密后内容不能变得过长,加密解密需要效率高,至于安全性,被
- 关于《回访确认》这件事情,在我blog和5Gme的回复里普遍出现这么几个疑问:1、下了订单却放弃支付的心理因素是什么?2、回访电话可以促进订
- 一,前言今天做的东西,还算可以,修改了若干个bug,自己又写成功的写了几个bug。增加了一个功能——
- 很高兴参加了这一期的薯片会,认识了几个朋友~~不料的却是今天我要来总结一下本次薯片会我们总共讨论了三个议题:A、 如何让“用户”更容易识别超
- 前言随着圣诞的到来,大家纷纷@官方微信给自己的头像加上一顶圣诞帽。当然这种事情用很多P图软件都可以做到。但是作为一个学习图像处理的技术人,还
- SqlServer帮助中对扩展属性的描述是: The Extended Properties property sets or retrie
- 看lifesinger的《由Kimi找茬想到的》,我想到的:1、 我不同意将“合并付款”定调在“很多卖家都需要”。这个“很多”在卖家里面大概
- 本文实例讲述了Python实现正弦信号的时域波形和频谱图。分享给大家供大家参考,具体如下:# -*- coding: utf-8 -*-#