属性访问
•__getattr__(self, name)
–定义当用户试图获取一个不存在的属性时的行为
•__getattribute__(self, name)
–定义当该类的属性被访问时的行为
•__setattr__(self, name, value)
–定义当一个属性被设置时的行为
•__delattr__(self, name)
–定义当一个属性被删除时的行为
实例1:
1 class C:
2 def __getattribute__(self, name):
3 print('getattribute')
4 # 使用 super() 调用 object 基类的 __getattribute__ 方法
5 return super().__getattribute__(name)
6
7 def __setattr__(self, name, value):
8 print('setattr')
9 super().__setattr__(name, value)
10
11 def __delattr__(self, name):
12 print('delattr')
13 super().__delattr__(name)
14
15 def __getattr__(self, name):
16 print('getattr')
17
18 >>> c = C()
19 >>> c.x
20 getattribute
21 getattr
22 >>> c.x = 1
23 setattr
24 >>> c.x
25 getattribute
26 1
27 >>> del c.x
28 delattr
29 >>> setattr(c,'y','Yellow')
30 setattr
练习要求
•写一个矩形类,默认有宽和高两个属性;
•如果为一个叫square的属性赋值,那么说明这是一个正方形,值就是正方形的边长,此时宽和高都应该等于边长。
实例2:
1 class Rectangle:
2 def __init__(self, width=0, height=0):
3 self.width = width
4 self.height = height
5
6 def __setattr__(self, name, value):#一发生赋值操作,则会触发__setattr__()魔法方法
7 if name == 'square':#判断name属性是否为正方形
8 self.width = value
9 self.height = value
10 else:
11 self.__dict__[name] = value
12
13 def getArea(self):
14 return self.width * self.height
15
16 >>> r1 = Rectangle(4,5)
17 >>> r1.getArea()
18 20
19 >>> r1.square = 10
20 >>> r1.getArea()
21 100