class Rectangle:
def __init__ (self):
self.width = 0
self.height = 0
def __setattr__(self, name, value):
if name == 'size':
print("hello")
self.width = value
self.height = value
else:
print("hahaha")
self. __dict__[name] = value
def __getattr__(self, name):
if name == 'size':
print("HeiHei")
return self.width, self.height
else:
raise AttributeError()
t=Rectangle()
t.size=10
print(t.size)
总的来说,以双短划线开头的函数称之为魔法方法,在赋值的时候会自动调用__setattr__,在获取属性的时候则会调用__gettattr__,如果你能猜出上面代码的输出结果,说明你就对这两个函数基本理解啦!
输出:
hahaha
hahaha
hello
hahaha
hahaha
HeiHei
(10, 10)