|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class C:
def __init__(self,width = 1, height = 2):
pass
def __getattr__(self,name):
print('getattr')
def __getattribute__(self,name):
print('getattribute')
return super().__getattribute__(name)
def __setattr__(self,name,value):
print('setattr')
if name == 'square':
self.width = value
self.height = value
else:
super().__setattr__(name,value)
def __delattr__(self,name):
print('delattr')
super().__delattr__(name)
def get_area(self):
print(1)
c = C()
print(c.get_area())
这个显示的结果会打印出一个“getattribute”,但是我根本就没有调用过类的属性,难道只调用方法,也会调用getattribute吗?
会呀,你不知道这个魔术方法你就用。看看官方文档
Called unconditionally to implement attribute accesses for instances of the class.
意思就是无条件地调用实现类的实例的属性访问。
只要你调用了类的实例就会执行
|
|