为什么尝试通过Python属性设置“points”会导致无限递归?
使用Python 3
import Task
myTask = Task.Task("Test",-5)
myTask.points = -7
print(myTask)
class Task:
def __init__(self,name="",points=0,times_done=0):
self.name = name
self.points = points
self.times_done = times_done
@property
def points(self):
return self.points
@points.setter
def points(self, points):
if (points < 0):
self.points = 0
else:
self.points = points
def __str__(self):
return "The task '" + self.name + "' is worth " + str(self.points) + " and has been completed " + str(self.times_done) + " times."
当使用值-5构造它(通过属性应该将其设置为0)时,它在setter函数/装饰器@points.setter
中的行self.points = points
上无限递归。
谢谢!
object
来复制:class Task(object)
。 - falsetru