标签:python python-3-x recursion decorator getter-setter
为什么尝试通过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-3-x,recursion,decorator,getter-setter 来源: https://codeday.me/bug/20190828/1753050.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。