___setattr__魔方方法
一定要注意防止无限递归
当在此方法内部给属性赋值的时候,那会调用此方法,又会重新赋值,无限重复
最后要归于super是种解决方法。或者用dict方法。  
 1 class Recangle:
 2     def __init__(self,width = 0,heigh = 0):
 3         self.width = width
 4         self.heigh = heigh
 5 
 6     def __setattr__(self,name,value):
 7         if name == 'square':
 8             self.width = value
 9             self.heigh = value
10         else:
11             print('else被执行了')
12             super().__setattr__(name,value)
13             
14 
15     def getArea(self):
16         return self.width * self.heigh
17 
18 a = Recangle(4,5)
19 print(a.getArea())
20 a.square = 10
21 print(a.getArea())
22 a.width = 100
23 print(a.getArea())
24 
25     
###运行结果
else被执行了
else被执行了
20
else被执行了
else被执行了
100
else被执行了
1000

  

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!