1

I just typed the code bellow. I expected John to be a memeber of team_B only. When I run the code, John is beeing added to both teams, even when I use "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")

Could anyone explain this and help me fix it?

1 Answer 1

3

Currently players is a class variable that is shared between all team objects, you want each instance to have it's own list of players.

class Team:
    def __init__(self):
        self.players = []

the __init__ code is run on object construction, note the self keyword, this refers to this current instance of a Team.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.