问题描述
我一直在使用 deepcopy 函数和 copy 函数,但我遇到了同样的问题.就像副本是引用(或指针)而不是正确的副本.我正在使用 Python 处理数据记录(类),也许是这样.我给你看一个例子:
I have been playing with the deepcopy function and the copy function and I get the same issue with both of them. It is like the copy was a reference (or a pointer) instead of a proper copy. I am working with data records (classes) in Python, maybe it could be that.. I show you an example:
>>> 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 数据记录中的 score 参数.
Now I increment the score parameter in player1 data record.
>>> 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.它是可变的而不是不可变的.
WHY HAS PLAYER 3 CHANGED? I just incremented a parameter in player1, not player3. It is mutable instead of immutable.
提前致谢.
推荐答案
问题是你实际上是在复制类定义而不是类的实例.
The problem is that you are actually copying the class definition and not an instance of the class.
代码的另一个问题是属性 age
和 score
是类的一部分,将在该类的所有实例之间共享.这可能不是您想要的.
Another problem of the code is that the attributes age
and score
are part of the class and will be shared between all instances of that class. This is probably not what you intended.
你可能想做的是:
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
这篇关于Python copy.deepcopy() 函数无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!