[英]These two codes should do exactly the same thing, but the first one doesn't work as I expect
蟒蛇
請解釋為什么這兩個代碼的工作方式不同。.實際上,我正在嘗試制作一種AI,其中在最初的幾代中,人們將朝着隨機的方向前進。 為了保持代碼的簡單我已經提供了自己的大腦一些隨機的方向 。
有一個為個人提供大腦的個人課程。 它也具有使孩子返回與父母完全相同的大腦(意味着相同的進入方向)的功能。
我有兩個代碼:
第一:當父項中的某些方向發生變化時,子項中的同一事物也發生了變化(或者,如果子項中的更改了,父項中的變化也發生了變化),這是我不想發生的。
第二:這不是完全屬於我的(這就是為什么我真的不知道它為什么起作用的原因),但是它可以正常工作。 父級中更改的某些方向在子級中不變,反之亦然。
請有人解釋我的區別,以及為什么第一個不起作用。 非常感謝您的回答。
第一:
class Brain():
def __init__(self):
self.directions = [[1, 2], [5, 3], [7, 4], [1, 5]]
class Individual():
def __init__(self):
self.brain = Brain()
def getChild(self):
child = Individual()
child.brain = self.brain
return child
parent = Individual()
child = parent.getChild()
parent.brain.directions[0] = [5, 2]
print(parent.brain.directions)
print(child.brain.directions)
[[5,2],[5,3],[7,4],[1,5]]
[[5,2],[5,3],[7,4],[1,5]]
第二個:
class Brain():
def __init__(self):
self.directions = [[1, 2], [5, 3], [7, 4], [1, 5]]
def clone(self):
clone = Brain()
for i, j in enumerate(self.directions):
clone.directions[i] = j
return clone
class Individual():
def __init__(self):
self.brain = Brain()
def getChild(self):
child = Individual()
child.brain = self.brain.clone()
return child
parent = Individual()
child = parent.getChild()
parent.brain.directions[0] = [5, 2]
print(parent.brain.directions)
print(child.brain.directions)
[[5,2],[5,3],[7,4],[1,5]]
[[1,2],[5,3],[7,4],[1,5]]
在第一個代碼中,設置child.brain = self.brain
並沒有達到您的期望。 那是一個淺表副本,意味着它只是創建一個指向Brain()
相同實例的新指針。 因此,現在child.brain
和self.brain
都指向內存中的同一Brain()
。
在第二個代碼中,您正在制作深層副本。 因此,您實際上是在內存中分配另一個Brain()
。 現在child.brain
和parent.brain
指向內存中它們自己的Brain()
單獨實例。
在第一種情況下,您指的是同一對象。 在第一種情況下,嘗試添加以下打印語句。
print (id(parent.brain))
print (id(child.brain))
在第一種情況下,有Brain()的新參考。 您可以看到它的處理方式。
class Brain():
def __init__(self):
self.directions = [[1, 2], [5, 3], [7, 4], [1, 5]]
class Individual():
def __init__(self):
self.brain = Brain()
def getChild(self):
child = Individual()
child.brain = Brain()
return child
parent = Individual()
child = parent.getChild()
parent.brain.directions[0] = [5, 2]
print(parent.brain.directions)
print(child.brain.directions)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.