看起来两个对象共享相同的非静态/非全局变量,我很困惑这是怎么回事,见下文:
class Pop:
def __init__(self):
self.n = 2
self.w = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
self.w_min = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self.w_max = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
def populate(self, __run):
for i in range(self.n):
self.varients.append(Varient(self))
for x in range(len(self.varients[i].w)):
self.varients[i].w[x] = randint(self.varients[i].w_min[x] * 100,
self.varients[i].w_max[x] * 100) / 100
else:
self.varients[i].w[x] = randint(self.varients[i].w_min[x] * 100,
self.varients[i].w_max[x] * 100) / 100
print(self.varients[i].w)
print(self.varients[0].w)
print(self.varients[1].w)
for x in range(len(self.varients[1].w)):
self.varients[1].w[x] = 1
print(self.varients[0].w)
print(self.varients[1].w)
class Varient(Pop):
def __init__(self, parent):
super().__init__()
self.w = parent.w
self.w_min = parent.w_min
self.w_max = parent.w_max
这是我看到的输出:
[1.0, 1.0, 0.86, 0.685, 0.925, 0.735, 0.35, 0.825, 0.31, 0.62, 0.71, 0.88]
[1.0, 1.0, 0.565, 0.575, 0.95, 0.405, 0.605, 0.48, 0.42, 0.445, 0.745, 0.41]
[1.0, 1.0, 0.565, 0.575, 0.95, 0.405, 0.605, 0.48, 0.42, 0.445, 0.745, 0.41]
[1.0, 1.0, 0.565, 0.575, 0.95, 0.405, 0.605, 0.48, 0.42, 0.445, 0.745, 0.41]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
当我更改" w"的值时对象" self.varients [1]"它以某种方式改变了" self.varients [0]"的价值。如果我通过指针这对我来说是有意义的,但我不明白为什么会发生这种情况?