|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 17623095765 于 2020-12-22 13:29 编辑
- # p12_5.py
- 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
复制代码
- >>>r1=Rectangle(4,5)
- >>>r1.getArea()
- 20
- >>>square=10
复制代码
当square=10时,触发__setattr__,调用if里面的 self.width=value,也就是r1.width=10,这里出现‘=’,那么应该调用__setattr__,因为‘name’==‘square’,然后无限递归下去。
但是不会,不知道哪里错了。
本帖最后由 小伤口 于 2020-12-22 10:20 编辑
- >>> r1=Rectangle(4,5)
- >>> r1.getArea()
- 20
- >>> r1.square=10
- >>> r1.getArea()
- 100
- >>>
复制代码
这样调用才会触发__setattr__,
square=10这样不过是普通赋值而已
话说你用的是 r1=Rectangle(4,5)
为什莫 你写成 r.getArea()这样也能出结果

|
|