__getattr__,getattribute,setattr,delattr的區別
阿新 • • 發佈:2018-09-15
super() def error: .get python pro clas line ror
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的區別