Discuss / Python / Homework,要点:返回时避免造成递归调用自己

Homework,要点:返回时避免造成递归调用自己

Topic source

郝仁E哥

#1 Created at ... [Delete] [Delete and Lock User]

(1)看了评论里很多人执着于加下划线,然后我去查到:(_x:单置下划线表示private(私有化)属性或方法,说是会永久改变width这个属性查找时的特性(改由obj.dict提供了)) (2)不过也可以不定义成这样,如我下面的代码:所有的返回我都设置成了return (new属性),避免和def width(self) 的width相同就可以了 否则,若写成 return self.width 的结果就是不断地递归调用自己,就会报出错误:RecursionError: maximum recursion depth exceeded,达到了递归的最大深度而出错。 综上,就是返回时起个别名避免陷入死循环的递归调用自己就可以了,我的理解就是这样。。

<code>

class Screen(object):

@property
def width(self):
    return self.newWidth #一定要和width不一样,否则导致递归调用
@width.setter
def width(self,value):
    self.newWidth = value

@property
def height(self):
    return self.newHeight
@height.setter
def height(self,value):
    self.newHeight = value

@property
def resolution(self):
    return self.newWidth * self.newHeight

  • 1

Reply