__getattr__,getattribute,setattr,delattr的区别

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了__getattr__,getattribute,setattr,delattr的区别相关的知识,希望对你有一定的参考价值。

class C:
    def __getattr__(self, name):
        print(1)
        return super().__getattr__(name)

    def __getattribute__(self, name):
        print(2)
        return super().__getattribute__(name)

    def __setattr__(self, name, value):
        print(3)
        super().__setattr__(name, value)

    def __delattr__(self, name):
        print(4)
        super().__delattr__(name)

c = C()
c.x
# 显示结果为:

Traceback (most recent call last):
2
  File "E:/Python Program/test.py", line 128, in <module>
1
    c.x
  File "E:/Python Program/test.py", line 113, in __getattr__
    return super().__getattr__(name)
AttributeError: ‘super‘ object has no attribute ‘__getattr__‘

原因: 
首先c.x会先调用getattribute()魔法方法,打印2;
然后调用super().getattribute(),找不到属性名x,
因此会紧接着调用getattr()魔法方法,于是打印1,
然后调用super().getattr()。但是Python会告诉你AttrError,super对象木有getattr()!!

以上是关于__getattr__,getattribute,setattr,delattr的区别的主要内容,如果未能解决你的问题,请参考以下文章

7.2__getattr____getattribute__魔法函数

python中__getattr__和__getattribute__区别

python3中__get__,__getattr__,__getattribute__的区别

__getattribute__

`__getattribute__` 和 `__getattr__` 中的错误处理

python中__get__,__getattr__,__getattribute__的区别