PythonMastery

Class variables in Python

A class variable is shared by every object of the class. Count how many objects were created, and see the mistake of using a list as a class variable.

A class variable is defined in the class body, outside any method. There is one copy of it, shared by every object. An instance variable is set on self, and each object has its own.

The program

python
class Player:
    count = 0  # class variable: one value for the whole class

    def __init__(self, name):
        self.name = name  # instance variable: one per player
        Player.count += 1

    @classmethod
    def how_many(cls):
        return cls.count


ada = Player("Ada")
alan = Player("Alan")
grace = Player("Grace")

print("Players created:", Player.how_many())
print("Read through an object:", ada.count)
print("Names:", ada.name, alan.name, grace.name)
output
Players created: 3
Read through an object: 3
Names: Ada Alan Grace

How it works

A shared list by mistake

A class variable that holds a list is shared too. This is a common bug:

python
class Team:
    members = []  # shared by every team

    def add(self, name):
        self.members.append(name)


red = Team()
blue = Team()
red.add("Linus")
print("Blue team:", blue.members)


class FixedTeam:
    def __init__(self):
        self.members = []  # a new list for each team

    def add(self, name):
        self.members.append(name)


red = FixedTeam()
blue = FixedTeam()
red.add("Linus")
print("Blue team:", blue.members)
output
Blue team: ['Linus']
Blue team: []

self.members.append(...) does not create anything new on the object. It finds the one list on the class and changes it. Create the list in __init__ so that each object gets its own.

Learn the idea: Object-Oriented Programming