码迷,mamicode.com
首页 > 其他好文 > 详细

__getattr__,getattribute,setattr,delattr的区别

时间:2018-09-15 17:32:55      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:结果   ace   调用   attr   traceback   对象   int   python   ram   

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的区别

标签:结果   ace   调用   attr   traceback   对象   int   python   ram   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!