回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p><strong>Python</strong></p>
<p>请解释为什么这两种代码的工作方式不同。。
事实上,我正在尝试制造一种人工智能,在最初的几代人中,个体将朝着随机的方向发展。为了保持代码简单,我在<em>大脑</em>中提供了一些随机的<em>方向</em></p>
<p>有一个<em>个体</em>类给个体一个大脑。它还有一个函数,返回一个与父母大脑完全相同的孩子(意味着要进入的方向相同)</p>
<p>我有两个密码:</p>
<p><strong>首先:</strong>当父级中的某些方向发生更改时,子级中也会发生相同的更改(或者如果子级中发生更改,则父级中也会发生更改),这是我不希望发生的</p>
<p><strong>第二:</strong>这个不完全是我的(这就是为什么我真的不知道它为什么工作),但它工作得很好。在父级中改变的某些方向在子级中不改变,反之亦然</p>
<p>请有人给我解释一下区别,为什么第一个不起作用。我非常感谢你的回答。
<br/><br/><br/>
第一个:</p>
<pre><code>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)
</code></pre>
<blockquote>
<p>[ [5, 2], [5, 3], [7, 4], [1, 5] ]</p>
<p>[ [5, 2], [5, 3], [7, 4], [1, 5] ]</p>
</blockquote>
<p><br/><br/>第二个:</p>
<pre><code>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)
</code></pre>
<blockquote>
<p>[ [5, 2], [5, 3], [7, 4], [1, 5] ]</p>
<p>[ [1, 2], [5, 3], [7, 4], [1, 5] ]</p>
</blockquote>