我刚刚输入了代码。我希望约翰只能成为team_b的成员。当我运行代码时,即使我使用" deepcopy",约翰都将蜜蜂添加到两个团队中:
import copy
class team:
players = []
team_A = team()
team_A.players.append("Tom")
team_A.players.append("Peter")
team_A.players.append("Mario")
team_B = copy.deepcopy(team_A)
team_B.players.append("John")
任何人都可以解释一下并帮助我修复它吗?
当前 players
是一个类变量,在> all 团队对象之间共享,您希望每个实例都有其自己的玩家列表。
class Team:
def __init__(self):
self.players = []
__init__
代码是在对象构造上运行的,请注意self
关键字,这是指团队的当前实例。