2
class GameState:
    def __init__(self):
        '''initializes the players turn'''
        self._player_turn = 'BLACK'
    def change_player_white(self):
        self._player_turn = 'WHITE'
    def p_move(self):
        return self._player_turn

if I call

project41.GameState().change_player_white()
print(project41.GameState().p_move())

it still prints out 'BLACK'

Juergen
  • 12,378
  • 7
  • 39
  • 55
dustinyourface
  • 313
  • 1
  • 3
  • 9

3 Answers3

1

Each time you call project41.GameState() you are creating a new GameState object. Instead, what you may want is:

my_game = project41.GameState()
my_game.change_player_white()

print(my_game.p_move())

If you really want a variable that is shared by all instances of your class, do see the Class and Instance Variables section in the docs.

aganders3
  • 5,838
  • 26
  • 30
1

Each call to GameState() creates a new instance. You created an instance, changed the player to white, and then discarded that player and created a new one on the following line. Try this:

state = project41.GameState()
state.change_player_white()
print(state.p_move())

Incidentally, your _player_turn is not a class attribute, but an instance attribute.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Whats the difference between a class attribute and an instance attribute? – dustinyourface Feb 26 '15 at 23:25
  • @dustinyourface: See [this question](http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) and many other resources that can be found by googling. – BrenBarn Feb 27 '15 at 04:52
0

You are creating a new instance of a GameState object with each of your calls.

Jamerson
  • 474
  • 3
  • 14