飘逸的python - __get__ vs __getattr__ vs __getattribute__以及属性的搜索策略
来源:互联网 发布:a算法八数码 编辑:程序博客网 时间:2024/05/29 14:24
区别:
__getattribute__:是无条件被调用.对任何对象的属性访问时,都会隐式的调用__getattribute__方法,比如调用t.__dict__,其实执行了t.__getattribute__("__dict__")函数.所以如果我们在重载__getattribute__中又调用__dict__的话,会无限递归,用object大神来避免,即object.__getattribute__(self, name).
__getattr__:只有__getattribute__找不到的时候,才会调用__getattr__.__get__:是descriptor.
假设我们有个类A,其中a是A的实例
a.x时发生了什么?属性的lookup顺序如下:
- 如果重载了__getattribute__,则调用.
- a.__dict__, 实例中是不允许有descriptor的,所以不会遇到descriptor
- A.__dict__, 也即a.__class__.__dict__ .如果遇到了descriptor,优先调用descriptor.
- 沿着继承链搜索父类.搜索a.__class__.__bases__中的所有__dict__. 如果有多重继承且是菱形继承的情况,按MRO(Method Resolution Order)顺序搜索.
ps.从上面可以看到,dot(.)操作是昂贵的,很多的隐式调用,特别注重性能的话,在高频的循环内,可以考虑绑定给一个临时局部变量.
下面给个代码片段大家自己去把玩探索.
class C(object): def __setattr__(self, name, value): print "__setattr__ called:", name, value object.__setattr__(self, name, value) def __getattr__(self, name): print "__getattr__ called:", name def __getattribute__(self, name): print "__getattribute__ called:",name return object.__getattribute__(self, name)c = C()c.x = "foo"print c.__dict__['x']print c.x
13 0
- 飘逸的python - __get__ vs __getattr__ vs __getattribute__以及属性的搜索策略
- python中__get__,__getattr__,__getattribute__的区别
- python中__get__,__getattr__,__getattribute__的区别
- python中__get__,__getattr__,__getattribute__的区别
- python中__get__,__getattr__,__getattribute__的区别
- python __get__ __getattr__ __getattribute__
- 详解Python中 __get__和__getattr__和__getattribute__的区别
- python3中__get__,__getattr__,__getattribute__的区别
- Python __getattribute__ vs __getattr__ 浅谈
- Python __getattribute__、__getattr__、__get__总结
- __getattr__ VS __getattribute__
- python总结(五):__get__、__getattr__、__getitem__、__getattribute__之间的差异与联系
- python __getattribute__ 和 __getattr__的区别
- python中__getattr__,__setattr__,__getattribute__的区别
- python中__get__, __getattr__和__getattribute__区别说明
- 飘逸的python - str vs. repr
- __getattr__和__getattribute__的区别
- python中__getattribute__与__getattr__调用时的区别
- iOS 扩展机制category与associative
- SQL Server uses more memory than "max server memory"
- CodeForces 191C 树链剖分 第4遍
- codechef Chef and Rainbow Array - 2
- Android动画之Property Animation(四)
- 飘逸的python - __get__ vs __getattr__ vs __getattribute__以及属性的搜索策略
- Jaxb处理java对象和xml之间转换常用的annotation
- 运行vs编译出的exe文件
- <objc/runtime.h>中Associative机制(在button以及block传值)
- JDBC总结
- QtQuick桌面应用开发指导 3)实现UI和功能_B 4)动态管理Note对象_A
- 如何在 AutoLayout 中使用 UIScrollView (多个ContentView)
- 解决webBrowser 访问出现"为了保护您的安全" 的警告 和 开启IIS目录浏览功能
- Android Studio 快捷键整理分享