Reputation: 13
I am new to python so I did some digging and from what I understand the member variable of a class will update in all instances of that class regardless of which instance you modified it with. However, it doesn't seem that the same should happen with instance variables however when I run this block of code...
class Game(object):
def__init__(self, active_turn, board):
self.active_turn = active_turn
self.board = board
game = Game(1,[1,0,0,0,0,0,0,0,0])
move = 3
print(game.board, "\n")
possible_game = Game(game.active_turn*-1,game.board)
print(game.board)
print(possible_game.board, "\n")
possible_game.board[move] = possible_game.active_turn
print(game.board)
print(possible_game.board, "\n")
game.board[move+1] = game.active_turn
print(game.board)
print(possible_game.board)
I get this output...
[1, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, -1, 0, 0, 0, 0, 0]
[1, 0, 0, -1, 0, 0, 0, 0, 0]
[1, 0, 0, -1, 1, 0, 0, 0, 0]
[1, 0, 0, -1, 1, 0, 0, 0, 0]
The board variable is updating in each instance of the Game class even though I am only changing it in one of them. Does anyone know why this is happening and what I could do to avoid it?
Thanks, Nick
Upvotes: 1
Views: 78
Reputation: 19368
use copy
>>> a = [1,2,3]
>>> from copy import copy
>>> b = copy(a)
>>> b
[1, 2, 3]
>>> b[1] = 5
>>> b
[1, 5, 3]
>>> a
[1, 2, 3]
>>>
To truely understand what's under the hood, you should learn about Python DataModel. The official doc is easy to follow.
To be short, list
are mutable
type in Python, which means that if you assign a list object to multiple variables, they are actually pointing to the same list object, thus changing one of them will affect others.
On the other hand, string
, int
, tuple
, ... are immutable
data type.
if you assign a=1
then a=2
, 1
and 2
are different int objects, i.e. 1
does not become 2
, because int
are immutable, they can't be modified.
Upvotes: 3
Reputation: 53535
You're using the same board
when you create both instances - so when one of them updates the board - the change is reflected in the other as well.
game = Game(1,[1,0,0,0,0,0,0,0,0]) # first instance - you create the board here
...
possible_game = Game(game.active_turn*-1,game.board) # second instance - you pass the same board (game.board) to the constructor
Upvotes: 3