Python copy.deepcopy()函数无法正常工作 [英] Python copy.deepcopy() function not working properly

查看:411
本文介绍了Python copy.deepcopy()函数无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用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

现在我增加玩家1数据记录中的得分参数.

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.

代码的另一个问题是属性agescore是该类的一部分,并且将在该类的所有实例之间共享.这可能不是您想要的.

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()函数无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆