首页 > 其他 > 详细

__getattr__,getattribute,setattr,delattr的区别

时间:2018-09-15 17:30:59      阅读:187      评论:0      收藏:0      [点我收藏+]
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的区别

原文:http://blog.51cto.com/13914991/2175589

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!