Understanding class-wide variables that should be tied to object instances

oop, python

Solution

When you say,

class Player:
    positions = []

`positions` will be a class variable and the same object is used by all the instances of the class. You can confirm by this

player1, player2 = Player(), Player()
print player1.positions is player2.positions    # True
print Player.positions is player1.positions     # True

If you want to create instance variables (separate `positions` variable for each and every instance of `Player`), you can create that in `__init__` function. It is a special initializer function, which gets the current actual object as the first parameter. You can create `positions` variable and attach it to that object like this

class Player:
    def __init__(self):
        self.positions = []

player1, player2 = Player(), Player()
print player1.positions is player2.positions    # False

Here, `self` refers to the newly constructed object and you are creating a new variable in that object by `self.positions` and you are initializing it with an empty list by

self.positions = []

So, whenever you create a new instances of `Player`, `self` will refer to the new instance created and new variable `positions` will be created on every instance, which means separate `positions` variable for each and every instance.

And whenever `move` is called, you don't have to create a new `position` variable on `self`. Instead you can do this

def move(self, position):
    self.positions.append(position)

If you are using Python 2.x, its better to use new style classes, like this

class Player(object):
    def __init__(self):
        self.positions = []

Problem

Here is a class that assigns a symbol to a player. It should accept a move and add the move to the existing repository of moves of the player. ``` class Player: ...: positions = [] ...: def __init__(self,symbol): ...: self.symbol = symbol ...: def move(self,position): ...: self.position = position ...: self.positions.append(self.position) ``` My problem is that positions is behaving "globally" in the sense that it is not tied to an object instance, to demonstrate: ``` >>>a = Player('x') >>>b = Player('y') >>>a.move(1) >>>b.positions [1] ```

Original source