gpt4 book ai didi

python - 为什么尝试通过 Python 属性设置 "points"会导致无限递归?

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:37 24 4
gpt4 key购买 nike

为什么尝试通过 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),它会在设置函数/装饰 self.points = points 行上无限递归 @points.setter.

谢谢!

最佳答案

因为 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 属性设置 "points"会导致无限递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com