python __getattr__ & __getattribute__ 学习
实例属性的获取和拦截, 仅对实例属性(instance, variable)有效, 非类属性
getattr: 适用于未定义的属性, 即该属性在实例中以及对应的类的基类以及祖先类中都不存在
1. 动态处理事先未定义的属性, 可更好的实现数据隐藏, 当调用dir(obj)时只会显示初始化定义的正常的属性和方法
getattribute: 对于所有属性的访问都会调用该方法, 当属性不存在时会报错
1. 覆盖该方法之后,任何属性的访问都会调用用户自定义的__getattribute__()方法, 性能上会有所损耗.
- 当两个方法同步被重写, 要么在__getattribute__()中显示调用, 要么是触发AttributeError异常时, getattr()才会被调用
- 要避免无穷递归调用
- 如果访问未定义属性, 且在__getattr__中未跑出AttributeError异常或者显性的返回一个值, 则会返回None
参考: 编写高质量代码:改善Python程序的91个建议
class Attribute(object):
def __init__(self, name):
self.name = name
def __getattribute__(self, key):
try:
print('calling __getattribute__.{key}'.format(key=key))
# 调用超类
return super(Attribute, self).__getattribute__(key)
# return object.__getattribute__(self, key)
except KeyError:
return 'default'
except AttributeError as ex: # 捕获了该异常就不用调用__getattr__
print(ex)
def __getattr__(self, key):
# 什么时候被调用:
# 1.当属性不在实例以及基类和祖先类的__dict__
# 2. 当触发AtrributeError异常时(不仅仅是__getattribute__()引发的 AttributeError),porperty中定义的get()方法也会抛出异常
print('calling __getattr__.{key}'.format(key=key))
# return 'default'
测试 property, getattribute, __getattr__调用顺序
class A(object):
_c = 'test'
def __init__(self):
self.x = None
@property
def a(self):
print('using property to access attribute')
if self.x is None:
print('return value')
return 'a'
else:
print('error occured')
raise AttributeError
@a.setter
def a(self, value):
self.x = value
def __getattribute__(self, name):
print('using __getattribute__ to access attribute')
return object.__getattribute__(self, name)
def __getattr__(self, name):
print('using __getattr__ to access attribute')
print('attribute name: ', name)
return 'b'
if __name__ == '__main__':
a = Attribute('atest')
print(a.name)
print(a.test)
# 测试 property, __getattribute__, __getattr__调用顺序
# b = A()
# print(b.a)
# print('-'*50)
# b.a = 10
# print(b.a)
# print('-'*50)
# print(A._c)
defaultdict 和 魔法方法__missing__()
dict中并不存在__missing__()方法, 需要派生子类并重写__missing__()方法
# python 2.5 之前默认要自己重写__missing__方法
# python3以后 __missing__(key) called by __getitem__ for missing key;
class DefaultDict(dict):
def __init__(self, default_factory, *args, **kwargs):
super(DefaultDict, self).__init__(*args, **kwargs)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
self[key] = value = self.default_factory()
return value
python __getattr__ & __getattribute__ 学习的更多相关文章
- Python中__get__, __getattr__, __getattribute__的区别及延迟初始化
本节知识点 1.__get__, __getattr__, __getattribute__的区别 2.__getattr__巧妙应用 3.延迟初始化(lazy property) 1.__get__ ...
- Python - __getattr__和__getattribute__的区别
传送门 https://docs.python.org/3/reference/datamodel.html#object.__getattr__ https://docs.python.org/3/ ...
- Python 装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...
- Requests:Python HTTP Module学习笔记(一)(转)
Requests:Python HTTP Module学习笔记(一) 在学习用python写爬虫的时候用到了Requests这个Http网络库,这个库简单好用并且功能强大,完全可以代替python的标 ...
- 从Theano到Lasagne:基于Python的深度学习的框架和库
从Theano到Lasagne:基于Python的深度学习的框架和库 摘要:最近,深度神经网络以“Deep Dreams”形式在网站中如雨后春笋般出现,或是像谷歌研究原创论文中描述的那样:Incept ...
- Comprehensive learning path – Data Science in Python深入学习路径-使用python数据中学习
http://blog.csdn.net/pipisorry/article/details/44245575 关于怎么学习python,并将python用于数据科学.数据分析.机器学习中的一篇非常好 ...
- (转载)Python装饰器学习
转载出处:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方 ...
- python网络爬虫学习笔记
python网络爬虫学习笔记 By 钟桓 9月 4 2014 更新日期:9月 4 2014 文章文件夹 1. 介绍: 2. 从简单语句中開始: 3. 传送数据给server 4. HTTP头-描写叙述 ...
- Python装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 ? 1 2 3 4 5 6 7 8 # -*- ...
随机推荐
- redis 键值对 有效期设置
redis 键值对 有效期设置redis中可以使用expire命令设置一个键的生存时间, 到时间后redis会自动删除它<-----> 类比于javaweb系统临时数据 过期删除功能 ex ...
- concurrent (一)concurrent
参考文档: 跳跃表原理分析:https://blog.csdn.net/a1259109679/article/details/46442895 一.阻塞队列 ArrayBlockingQueue : ...
- windows上svn图标不显示 绿色对号
http://blog.csdn.net/fengyupeng/article/details/12514449 症状1:项目左侧导航栏表不能正常显示图标 方法:windows->prefere ...
- Beta冲刺(3/7)——2019.5.25
作业描述 课程 软件工程1916|W(福州大学) 团队名称 修!咻咻! 作业要求 项目Beta冲刺(团队) 团队目标 切实可行的计算机协会维修预约平台 开发工具 Eclipse 团队信息 队员学号 队 ...
- select列表遍历和触发事件
1.以下两种都是jquery获取select列表被选中的value.var strText=$("#select_id").find("option:selected&q ...
- ES6中的关键字 - const
const 关键字 1.声明后的值不可以修改: const name = "小康哥"; name = "小康"; // 报错,const为constant的缩写 ...
- 重学C语言之结构体
概念 结构体是一种构造类型,由若干个成员组成,成员可以是基本数据类型,或是另一个结构体 声明结构体 struct 结构体名 { 成员列表 }; 结构体名表示结构的类型名. 声明一个结构体表示创建一种新 ...
- AGC035
Contest Page A 唯一会做的题/kk 题目相当于要求相邻三个的异或和为\(0\). 当我们放入了三个数\(a,b,c\)时,接下来的放入顺序显然一定是\(a,b,c,a,b,c,...\) ...
- Java学习:集合双列Map
数据结构 数据结构: 数据结构_栈:先进后出 入口和出口在同一侧 数据结构_队列:先进先出 入口和出口在集合的两侧 数据结构_数组: 查询快:数组的地址是连续的,我们通过数组的首地址可以找到数组,通过 ...
- 50道Redis面试题及答案整理,史上最全!
在网上看到有关Redis的50道面试题,但是没有给出答案,之前我也在寻找这份Redis面试题的答案,今天特地把答案分享出来. 花了大量时间整理了这套Redis面试题及答案,希望对大家有帮助哈~ 弄明白 ...