Python: maximum recursion depth exceeded while calling a Python object when calling copy function
我有一个类粒子,它有一些参数和属性,如下所示。但是,当它到达函数setter的位置,并执行copy()函数时,我得到错误消息:runtimeerror:调用python对象时超过了最大递归深度。我尝试过不同的选项,比如deepcopy(),或者import sys.setrecursionlimit(10000),但是没有一个有效的……有人知道吗?这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 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 |
看起来您正在尝试使用
1 2 3 4 | @position.setter def position(self, newPosition): self.position = newPosition.copy() # ^^^^^^^^^^^^^^^ |
设置
1 2 3 | @property def position(self): return self.position |
这个吸气剂自己叫!
尝试在