另一个基于@Armin 评论的刺伤。这确实展示了相关的深拷贝行为:
import random
width = 5
height = 5
class Brain(object):
def __init__(self):
self.w = [[1]]
self.ix = [[1]]
def mutate(self):
self.w[0].append(1)
class Animal(object):
def __init__(self):
self.brain = Brain()
self.x = random.randint(0, width)
self.y = random.randint(0, height)
self.age = 0
self.fitness = 10
def reproduce(parent):
child = Animal()
child.brain.w= parent.brain.w[:]
child.brain.ix= parent.brain.ix[:]
child.x,child.y = random.randint(0,width),random.randint(0,height)
child.age = 0
child.fitness= 9 + parent.fitness/10 #parent.fitness/2
mutation = random.choice([0,1,1,1,1,1,1,1,1,2,3,4,5])
for b in range(mutation):
child.brain.mutate()
animals.append(child)
animals = []
parent = Animal()
animals.append(parent)
print parent.brain.w
#reproduce(parent)
import copy
reproduce(copy.deepcopy(parent))
for each in animals:
print each.brain.w
此处的解决方法是不要将状态值存储在您在对象之间复制的可变类型中;在这种情况下是一个列表,但它可以是任何可变对象。
编辑:您在原始代码中所做的是将内容复制parent.brain.w
到child.brain.w
. Python 具有分配给原始对象的属性,而不是对象或内容的副本(除非您使用该copy
模块)。文档很好地涵盖了这一点。简而言之,这意味着以下情况是正确的:
>>> a = [1, 2, 3, 4, 5]
>>> b = a
>>> b.append(6)
>>> b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a is b
True
也就是说,两者a
和b
都是同一个列表。那不是您正在做的事情。您正在将列表复制到对象中,但这是等效的:
>>> a = [[1, 2, 3]]
>>> b = []
>>> b = a[:] # What you are doing
>>> b is a
False
>>> b[0] is a[0]
True
>>> b[0].append(4)
>>> b[0]
[1, 2, 3, 4]
>>> a[0]
[1, 2, 3, 4]
如果您的类型不可变,那么当您修改它时,会创建一个新对象。例如,考虑一个有点等价的元组列表(它们是不可变的):
>>> a = [(1, 2, 3)]
>>> b = []
>>> b = a[:]
>>> b is a
False
>>> b[0] is a[0] # Initially the objects are the same
True
>>> b[0] += (4,) # Now a new object is created and overwrites b[0]
>>> b[0] is a[0]
False
>>> b[0]
(1, 2, 3, 4)
>>> a[0]
(1, 2, 3)