我有一个类“ RAR”,带有属性“ limit”(大小为“ limit”的向量)和parent1”(大小为“ size”的向量)。极限矢量由1到31的整数组成:[1,2,3 ...,31]。并且parent1由5个随机数组成,其限制为:[1,4,7,10,30]或[1,2,4,6,23]。我正在尝试创建一种方法,该方法将选择父类,并通过更改父1中的一个随机元素,将其更改为父1中尚未包含的另一个限制元素来对其进行修改。我已经完成此方法,但是正在修改原始父对象,不会发生什么,需要保留parent1。我已经像类方法一样完成了它,所以我不需要每次调用该方法时都给出极限矢量,因为它是一个类不可变的矢量。为什么代码会修改原始父对象,因为它是方法的局部变量?我该如何解决?
class RAR:
def __init__(self,parent1,limit):
self.parent1=#given vector parent1
self.limit=[i for i in range(1,limit+1)]
def mutation(self,parent): #this functions perform a mutation in a given parent, changing one of the stocks for another asset not included
cparent=parent #i tried this to see if creating another variable it wouldn't modigy the self.parent1
k=rand.randint(0,len(parent)-1)
a=parent.pop(k)
b=rand.randint(0,len(limit)-1)
while c!=1:
if check(b,cparent)==0 and b!=limit[a-1]:
print("Executed if.")
b=rand.randint(0,len(limit)-1)
c=1
print("For conference, a: "+str(a))
print("Sorted number: "+str(b))
cparent.append(b+1)
cparent=bubble(parent)
return parent
答案 0 :(得分:0)
如果我正确理解问题,那就是列表是可变的,并且您正在对其进行变异。只需在函数中进行复制:
def mutation(self, parent):
cparent = parent.copy() # <- here
k = rand.randint(0, len(cparent)-1)
a = cparent.pop(k)
... # etc.