我一直在使用深度复制功能和复制功能,并且我对它们都遇到了同样的问题。这就像副本是引用(或指针)而不是正确的副本。我正在Python中处理数据记录(类),也许可能是这样..我给你看一个例子:
>>> import copy
>>> class player1:
... age = 23
... score = 1
>>> class player2:
... age = 14
... score = 2
>>> player3 = copy.deepcopy(player1)
我打印参数。
>>> print player1.age, player1.score
23 1
>>> print player2.age, player2.score
14 2
>>> print player3.age, player3.score
23 1
现在我增加player1数据记录中的分数参数。
>>> player1.score += 3
我再次打印结果。
>>> print player1.age, player1.score
23 4
>>> print player2.age, player2.score
14 2
>>> print player3.age, player3.score
23 4
为什么玩家 3 发生了变化?
我只是增加了player1 中的一个参数,而不是player3 中的参数。它是可变的而不是不可变的。
提前致谢。
问题在于您实际上是在复制类定义而不是类的实例。
代码的另一个问题是属性age
and score
是类的一部分,并将在该类的所有实例之间共享。这可能不是您想要的。
您可能想要做的是:
import copy
class Player:
def __init__(self, age, score):
self.age = age
self.score = score
player1 = Player(23, 1)
player2 = Player(14, 2)
player3 = copy.deepcopy(player1)
player1.age += 1
print "player1.age", player1.age
print "player3.age", player3.age
这给了你你所期望的:
player1.age 24
player3.age 23
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)