Why are my different instance variables linking together in python -
i new python did digging , understand member variable of class update in instances of class regardless of instance modified with. however, doesn't seem same should happen instance variables when run 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 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 updating in each instance of game class though changing in 1 of them. know why happening , avoid it?
thanks, nick
you're using same board
when create both instances - when 1 of them updates board - change reflected in other well.
game = game(1,[1,0,0,0,0,0,0,0,0]) # first instance - create board here ... possible_game = game(game.active_turn*-1,game.board) # second instance - pass same board (game.board) constructor
Comments
Post a Comment