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 # -*- ...
随机推荐
- 关于qt creator各种假死的问题
来自CSDN网友( qq191329827)内容,亲自尝试,且经历一致: 我有两个笔记本,1个台式机,都装了qt, 然后,我的thinkpad x1c,装上之后creator各种假死,网上看了好多解决 ...
- Centos 6.X查看和设置时间时区
Centos 6.X系列操作系统的修改时区和时间的方法. 一.查看Centos的时区和时间 1.使用date命令查看Centos时区 [root@VM_centos ~]# date -R Mon, ...
- HashMap源码1
jdk1.8之前是数组+链表的形式,后面会介绍jdk1.8对hashMap的改动:数组+链表+红黑树 transient是Java语言的关键字,用来表示一个域不是该对象串行化的一部分. 当一个对象被串 ...
- centos安装nginx1.17
从yum源安装nginx> yum install -y nginx> nginx -vnginx version: nginx/1.12.2 安装依赖包yum install -y gc ...
- Selenium基础教程(三)自动化插件Katalon
Katalon-一款好用的selenium自动化测试插件 Selenium 框架是目前使用较广泛的开源自动化框架,一款好的.基于界面的录制工具对于初学者来说可以快速入门:对于老手来说可以提高开发自动化 ...
- Python3+PyCryptodome实现各种加密算法教程
一.说明 PyCryptodome是python一个强大的加密算法库,可以实现常见的单向加密.对称加密.非对称加密和流加密算法.直接pip安装即可: pip install pycryptodome ...
- Flutter 宽高比(比率)控件 AspectRatio
const AspectRatio({ Key key, @required this.aspectRatio, Widget child,}) void main() { runApp( n ...
- 封装:Cmd命令调用和常用命令
原文:封装:Cmd命令调用和常用命令 一.Cmd命令调用方法 1.静态方法调用 class Program { static void Main(string[] args) { // Todo :打 ...
- using 语句(C# 参考)(转载)
using 语句 提供可确保正确使用 IDisposable对象的方便语法. 示例 下面的示例演示如何使用 using 语句. using (var font1 = new Font("Ar ...
- laravel hash密码生成和密码验证
在laravel中 登录表单中的密码是用hash来生成的. 在生成密码需要用到 laravel框架中的方法(都是laravel封装好了的) bcrypt($password)方法,直接将获取到的pas ...