__getattr__
__getattr__在当前主流的Python版本中都可用,重载__getattr__方法对类及其实例未定义的属性有效。也就属性是说,如果访问的属性存在,就不会调用__getattr__方法。这个属性的存在,包括类属性和实例属性。

Python官方文档的定义

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name.

class ClassA:

    x = 'a'

    def __init__(self):
self.y = 'b' def __getattr__(self, item):
return '__getattr__' if __name__ == '__main__':
a = ClassA()
# 输出结果 a
print(a.x)
# 使用实例直接访问实例存在的实例属性时,不会调用__getattr__方法
# 输出结果 b
print(a.y)
# 使用实例直接访问实例不存在的实例属性时,会调用__getattr__方法
# 输出结果 __getattr__
print(a.z)

__getattribute__
__getattribute__仅在新式类中可用,重载__getattrbute__方法对类实例的每个属性访问都有效。

Python官方文档的定义

Called unconditionally to implement attribute accesses for instances of the class.

示例代码:

class ClassA:

    x = 'a'

    def __init__(self):
self.y = 'b' def __getattribute__(self, item):
return '__getattribute__' if __name__ == '__main__':
a = ClassA()
# 使用实例直接访问存在的类属性时,会调用__getattribute__方法
# 输出结果 __getattribute__
print(a.x)
# 使用实例直接访问实例存在的实例属性时,会调用__getattribute__方法
# 输出结果 __getattribute__
print(a.y)
# 使用实例直接访问实例不存在的实例属性时,也会调用__getattribute__方法
# 输出结果 __getattribute__
print(a.z)

运行结果:

__getattribute__
__getattribute__
__getattribute__

另外,当同时定义__getattribute__和__getattr__时,__getattr__方法不会再被调用,除非显示调用__getattr__方法或引发AttributeError异常。

示例代码(__getattr__方法不会再被调用):

class ClassA:

    def __getattr__(self, item):
print('__getattr__') def __getattribute__(self, item):
print('__getatttribute__') if __name__ == '__main__':
a = ClassA()
a.x

运行结果:

__getatttribute__

由于__getattr__只针对未定义属性的调用,所以它可以在自己的代码中自由地获取其他属性,而__getattribute__针对所有的属性运行,因此要十分注意避免在访问其他属性时,再次调用自身的递归循环。

当在__getattribute__代码块中,再次执行属性的获取操作时,会再次触发__getattribute__方法的调用,代码将会陷入无限递归,直到Python递归深度限制(重载__setter__方法也会有这个问题)。

示例代码(无限递归):

class ClassA:

    x = 'a'

    def __getattribute__(self, item):
print('__getattribute__')
return self.item if __name__ == '__main__':
a = ClassA()
a.x

运行结果引发异常,提示达到最大递归深度

ecursionError: maximum recursion depth exceeded

同时,也没办法通过从__dict__取值的方式来避免无限递归

class ClassA:

    x = 'a'

    def __getattribute__(self, name):
return self.__dict__[name] if __name__ == '__main__':
a = ClassA()
# 无限递归
a.x

为了避免无限递归,应该把获取属性的方法指向一个更高的超类,例如object(因为__getattribute__只在新式类中可用,而新式类所有的类都显式或隐式地继承自object,所以对于新式类来说,object是所有新式类的超类)。

修改代码(避免无限递归循环):

class ClassA:

    x = 'a'

    def __getattribute__(self, item):
print('__getattribute__')
return super().__getattribute__(self, item) if __name__ == '__main__':
a = ClassA()
print(a.x)

运行结果正常:

__getattribute__
a

参考资料:

https://docs.python.org/3/reference/datamodel.html

Python的__getattr__和__getattribute__的更多相关文章

  1. 浅谈Python 中 __getattr__与__getattribute__的区别

    __getattr__与__getattribute__均是一般实例属性截取函数(generic instance attribute interception method),其中,__getatt ...

  2. python魔法方法:__getattr__,__setattr__,__getattribute__

    python魔法方法:__getattr__,__setattr__,__getattribute__ 难得有时间看看书....静下心来好好的看了看Python..其实他真的没有自己最开始想的那么简单 ...

  3. python中的__getattr__、__getattribute__、__setattr__、__delattr__、__dir__

    __getattr__:     属性查找失败后,解释器会调用 __getattr__ 方法. class TmpTest: def __init__(self): self.tmp = 'tmp12 ...

  4. 第8.33节 Python中__getattr__以及__getattr__与__ getattribute__的关系深入剖析

    一. 引言 前面几节分别介绍了Python中属性操作捕获的三剑客:__ getattribute__方法.__setattr__方法.__delattr__方法,为什么__ getattribute_ ...

  5. 一些代码 II (ConfigParser、创建大文件的技巧、__getattr__和__getattribute__、docstring和装饰器、抽象方法)

    1. ConfigParser format.conf [DEFAULT] conn_str = %(dbn)s://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s ...

  6. python __setattr__, __getattr__, __delattr__, __call__

    python __setattr__, __getattr__, __delattr__, __call__ getattr `getattr`函数属于内建函数,可以通过函数名称获取 value = ...

  7. python之 __getattr__、__getattr__、__getitem__、__setitem__ 使用

    python之 __getattr__.__getattr__.__getitem__.__setitem__ 使用 __getattr__内置使用点号获取实例属性属性如 s.name,自调用__ge ...

  8. python魔法函数之__getattr__与__getattribute__

    getattr 在访问对象的属性不存在时,调用__getattr__,如果没有定义该魔法函数会报错 class Test: def __init__(self, name, age): self.na ...

  9. Python魔法方法__getattr__和__getattribute__详解

    在Python中有这两个魔法方法容易让人混淆:__getattr__和getattribute.通常我们会定义__getattr__而从来不会定义getattribute,下面我们来看看这两个的区别. ...

随机推荐

  1. 使用PowerApps快速构建基于主题的轻业务应用 —— 入门篇

    作者:陈希章 发表于 2017年12月12日 前言 在上一篇文章 基于Office 365的随需应变业务应用平台 中我提到,随着随需应变的业务需要,以及技术的发展,业务应用的开发的模式也有了深刻的变化 ...

  2. 一个看起来不像中年人的中年人,带着两个初出茅庐的小伙子儿,用git管理项目代码的进击之路

    一个中年人的孤独前行 我们这一代人,是上个世纪的人,活在当下,已然成为社会上的中流砥柱. 80年代生人,遥望我们的父辈,均是5.60年代的人,迟迟暮年,夕夕老矣.而我们,正当年,却又时光飞逝,很快便要 ...

  3. Java爬虫——网易云热评爬取

    爬取目标网址 :   http://music.163.com/#/song?id=409649818 需要爬取信息 :   网易云top13热评 使用之前的 HttpURLConnection 获取 ...

  4. DirectX:在graph自己主动连线中增加自己定义filter(graph中遍历filter)

    为客户提供的视频播放的filter的測试程序中,採用正向手动连接的方式(http://blog.csdn.net/mao0514/article/details/40535791).因为不同的视频压缩 ...

  5. Java基础(四)-异常处理机制及其设计

    本篇主要是记录自己所理解的Java异常处理机制(基于jdk1.7)以及怎么去处理和设计异常.还记得当初学习Java异常这块的时候都没怎么注意它的用途,以为就是简单的处理下异常,我避免程序出现这样错误就 ...

  6. Winform开发框架中工作流模块的业务表单开发

    在我们开发工作流的时候,往往需要设计到具体业务表单信息的编辑,有些是采用动态编辑的,有些则是在开发过程中处理的,各有各的优点,动态编辑的则方便维护各种各样的表单,但是数据的绑定及处理则比较麻烦,而自定 ...

  7. junit初探

    由于公司规模不大,所以测试方面一直不是很正规,都是做完一个功能,稍微测试一下,没有做单元测试,所以自然也没有接触过类似于junit这类测试的工具. 今天有空研究了一下junit,顾名思义,这是给jav ...

  8. 移动浏览器H5页面通过scheme打开本地应用

    在移动端浏览器H5页面中,点击按钮打开本地应用主要通过 scheme 协议.本文主要介绍如何在浏览器H5页面中通过 scheme 协议打开本地应用. scheme协议定义 scheme 是一种页面之间 ...

  9. SSH之免密登陆

    又来了,上头让小轩我在服务器中写一个Shell脚本,主要用来在机器B中定时备份机器A中的一些文件.那么,小轩是怎么想的呢? 在小轩的知识库里,现在有scp和ssh两个玩具.别的还真没有其他什么东西了. ...

  10. 在IDEA中实战Git(转载自)

    转载自:http://blog.csdn.net/autfish/article/details/52513465 工作中多人使用版本控制软件协作开发,常见的应用场景归纳如下: 假设小组中有两个人,组 ...