|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def __setattr__(self, name, value):
if name == 'square': ?
self.width = value ?
self.height = value ?
else:
super().__setattr__(name,value) ?
def getArea(self):
return self.width * self.height
见结尾打?的,为了防止无限递归,else后用了super(),但是if后为什么就可以不用调用基类的方法而防止递归呢
谢谢大家了
本帖最后由 MSK 于 2017-8-14 12:02 编辑
改一下代码:
- class Rectangle:
- def __init__(self, width=0, height=0):
- self.width = width
- self.height = height
- def __setattr__(self, name, value):
- if name == 'square':
- self.width = value
- self.height = value
- else:
- print('设置属性..')
- super().__setattr__(name,value)
- def getArea(self):
- return self.width * self.height
复制代码
运行结果:
- >>> rect = Rectangle()
- 设置属性..
- 设置属性..
- >>> rect.square = 8
- 设置属性..
- 设置属性..
复制代码
原因很简单,当执行self.width = value self.height = value时 同样产生递归,
只不过递归时进入了else所在的语块,通过super对width,height属性进行了赋值
|
|