为什么尝试通过Python属性设置“点”会导致无限递归?

为什么尝试通过Python属性设置“点”会导致无限递归?

使用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)构建它时,它会无限地递归到set.function / decoration @ points.setter中的self.points =点.

谢谢!

解决方法:

因为self.points = …叫setter;在setter中,执行self.points = …来调用setter;重复递归直到堆栈溢出.

通过使用其他名称,您可以阻止递归:例如self._points.

或者不使用self.points = …,使用self .__ dict __ [‘points’] = ..(同样适用于getter):

@property
def points(self):
    return self.__dict__['points']

@points.setter
def points(self, points):
    if points < 0:
        self.__dict__['points'] = 0
    else:
        self.__dict__['points'] = points
    # self.__dict__['points'] = max(0, points)
上一篇:Python函数装饰器错误


下一篇:python – 切换装饰器