Stephen Mason
Stephen Mason

Reputation: 357

Appending to attribute of a specific object, where objects are stored in a dict

I am having trouble appending an element to a list, where the list is an attribute of a custom class I have created. The object containing the list should be accessible through a dict.

For context, I am creating a game which can have multiple players, each player has a 'Player' object associated with them that tracks their socket, name, character a list of their previous moves and kill status:

class Player():
def __init__(self, sock, name, char, moves, kill_status):
    self.sock = sock
    self.name = name
    self.char = char
    self.moves = moves
    self.kill_status = kill_status

These Player objects are stored in the PLAYER dict, which resembles the following:

PLAYER = {
1: Player(sock, name, char, moves, kill_status)
2: Player(sock, name, char, moves, kill_status)
}

So that if I want to access the name for player1 for example, I simply use:

player1_name = PLAYER[1].name

the moves attribute is initially passed in as an empty list, so that I can append an individual player's moves as they make them.

The issue is that when i use

PLAYER[1].moves.append(move)

The move is added to the list of every player in the dict, so that even

PLAYER[2].moves

would return a list including the move I was trying to add to player 1

How can I add the move specifically to the list of Player it was made by?

EDIT:

This is how a create the dict initially:

moves = []

for i in range(1, LOBBY_SIZE + 1):
    PLAYER[i] = pi.Player(None, name, None, moves, kill_status)

Upvotes: 1

Views: 34

Answers (1)

gmds
gmds

Reputation: 19885

The problem is this:

moves = []

for i in range(1, LOBBY_SIZE + 1):
    PLAYER[i] = pi.Player(None, name, None, moves, kill_status)

What happens is that you are assigning the same list referred to by moves to each Player object.

You should do this:

for i in range(1, LOBBY_SIZE + 1):
    PLAYER[i] = pi.Player(None, name, None, [], kill_status)

Upvotes: 2

Related Questions