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 # -*- ...
随机推荐
- R 语言解压目录下的所有gz文件
setwd("GSE29431_RAW") # 进入目录 fileNames <- list.files() # 获取目录下的所有文件 sapply(fileNames, g ...
- zabbix php-fpm监控
#!/bin/bash################################### Zabbix monitoring script## php-fpm:# - anything avail ...
- 关于Echarts柱状图实现的细节
echarts柱状图显示数值[1] echarts2: itemStyle : { normal: {label : {show: true, position: 'top'}}}, echarts ...
- [Gamma]Scrum Meeting#9
github 本次会议项目由PM召开,时间为6月4日晚上10点30分 时长15分钟 任务表格 人员 昨日工作 下一步工作 木鬼 撰写博客,组织例会 撰写博客,组织例会 swoip 前端显示屏幕,翻译坐 ...
- 微信公众平台开发(150)——从新浪云SAE上传图片到图文消息
从新浪云SAE上传图片到图文消息,只能用于图文消息中, 没有个数限制 if (!empty($_FILES['qrcode']['name'])){ $filename = time()." ...
- Controller如何进行重定向跳转
因为在Controller的返回都是默认走视图解析器的InternalResourceViewResolver,而视图解析器都是进行请求转发,需要在返回时地址前加入字符redirect: 视图解析器不 ...
- docker入门实例(转载)
1.Docker 是什么?Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的镜像中,然后发布到任何流行的 Linux 或 Windows 机器上( 摘自百度 ) ...
- Python列表(list)所有元素的同一操作
针对很普遍的每个元素的操作会遍历每个元素进行操作. 这里给出了几种写法,列表每个元素自增等数学操作同理: 示例:整形列表ilist加1个数.元素类型转字符串: ilist = [1, 2, 3, 10 ...
- C# System.Reflection.Assembly动态加载资源文件
需求:需要做甘特图的显示,并且在甘特中加载图片.图片太多,写判断代码太多.用反射吧. 核心代码: try { if (stateColour < 0) return null; System.R ...
- 来自后端的逆袭 blazor简介 全栈的福音
背景 什么是SPA 什么是MPA MPA (Multi-page Application) 多页面应用指的就是最传统的 HTML 网页设计,早期的网站都是这样的设计,所之称为「网页设计」.使用 MPA ...