Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么要尝试设置;要点;通过Python属性导致无限递归?_Python_Python 3.x_Recursion_Decorator_Getter Setter - Fatal编程技术网

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

为什么要尝试设置;要点;通过Python属性导致无限递归?,python,python-3.x,recursion,decorator,getter-setter,Python,Python 3.x,Recursion,Decorator,Getter Setter,为什么试图通过Python属性设置“点”会导致无限递归 使用Python 3 import Task myTask = Task.Task("Test",-5) myTask.points = -7 print(myTask) 类任务: def uuu init uuuu(self,name=”“,points=0,times\u done=0): self.name=名称 self.points=点 self.times\u done=完成次数 @财产 def点(自身): 返回自我积

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

使用Python 3

import Task

myTask = Task.Task("Test",-5)

myTask.points = -7

print(myTask)

类任务:
def uuu init uuuu(self,name=”“,points=0,times\u done=0):
self.name=名称
self.points=点
self.times\u done=完成次数
@财产
def点(自身):
返回自我积分
@二传手
def点(自身,点):
如果(分数<0):
self.points=0
其他:
self.points=点
定义(自我):
返回“任务”'+self.name+“'值“+str(self.points)+”,并且已完成“+str(self.times_done)+”次。”

当它尝试用值-5构造它时(应该通过属性将其设置为0),它在setter函数/decoration
@points.setter.


谢谢

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

通过使用其他名称,可以防止递归:例如,
self.\u points

或者使用
self.points=…
,而不是使用
self.\uuu dict\uuu['points']=…
(与getter相同):

@属性
def点(自身):
返回自我。_udict__;['points']
@二传手
def点(自身,点):
如果点<0:
self._dict___['点]]=0
其他:
自我.u_指令_['points']=点数
#self._dict__['points']=最大值(0,点)

这是因为在
属性设置器中,它再次调用自己:

@points.setter
def points(self, points):
    if (points < 0):
        self.points = 0 # call itself again here
    else:
        self.points = points # call itself again here

我无法重现这个错误。你是否省略了任何代码?只有那些根本不应该相关的东西。我来编辑it@Julien,OP应该使用Python3.x。如果您使用的是Python2.x,通过继承
对象
,您可以复制:
类任务(对象)
。我使用的是Python3,是的
@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)
@points.setter
def points(self, points):
    if (points < 0):
        self.points = 0 # call itself again here
    else:
        self.points = points # call itself again here
class Task(object):
    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