Python:调用复制函数时,调用Python对象时超出了最大递归深度

问题描述:

我有一个 Particle 类,它具有一些参数和属性,如下所示。但是,当确实到达函数设置器的位置并执行了copy()函数时,我收到错误消息: RuntimeError:调用Python对象时超出了最大递归深度。我尝试了其他选项,例如 deepcopy() import sys sys.setrecursionlimit(10000),但它们都不起作用...有人有什么主意吗?这是我的代码:

I have a class Particle which has some parameters and attributes, as you can see below. But, when it does get to the function setter for position, and it executes the copy() function, I get the error message : RuntimeError: maximum recursion depth exceeded while calling a Python object. I've tried different options, like deepcopy(), or import sys sys.setrecursionlimit(10000) , but none of them worked... Does anyone have any idea? This is my code:

def initCost(n):
    a = random.randint(0,10)              #gram.
    b = random.randint(0,5)             #price
    return [random.randint(0,a*b) for i in range(n)]

costs = initCost(10)

class Particle:
    def __init__(self, n, maxWeight):
        self.position = [random.randint(0,1) for i in range(n)]  #position
        self.velocity = [0 for i in range(n)]                    #velocity
        #self.fit = self.fitness(self.position)
        self.bp = self.position.copy()                           #best position
        self.bf = self.fit                                 #best fitness
        self.evaluate()

    def fit(self, x):
        fitt = 0
        for i in range(len(x)-1):
            if (x[i] == 1):
                fitt = fitt + costs[i]
        return fitt

    def evaluate(self):
        """ evaluates the particle """
        self.fitness = self.fit(self.position)

    @property
    def position(self):
        return self.position

    @property
    def bp(self):
        return self.bp

    @property
    def bf(self):
        return self.bf

    @position.setter
    def position(self, newPosition):
        self.position = newPosition.copy()
        #self.position = newPosition[:]
        self.evaluate()
        # automatic update of particle's memory
        if (self.fit<self.bf):
            self.bp = self.position
            self.bf  = self.fit


您似乎正在尝试使用 position 作为属性的名称以及支持该属性的普通属性。例如,

It looks like you're trying to use position as the name of both the property and the ordinary attribute backing it. For example,

@position.setter
def position(self, newPosition):
    self.position = newPosition.copy()
#   ^^^^^^^^^^^^^^^

这种尝试设置 self.position 的尝试将使用您正在定义的设置器!同样,

This attempt to set self.position will use the setter you're defining! Similarly,

@property
def position(self):
    return self.position

这个吸气剂只是自称!

尝试使用 position 属性定义内的code> self.position 不会绕过该属性。如果您需要常规属性作为属性的后盾,则可以使用其他名称,例如 self._position 或其他名称。

Trying to use self.position inside the position property definition won't bypass the property. If you want a "regular" attribute backing the property, call it something else, like self._position or something.