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
Player.count += 1changes the class variable, so every new player adds 1 to the same counter.ada.countalso works for reading. Python looks forcounton the object first, does not find it, and then looks on the class.@classmethodmakes a method that receives the class (cls) instead of an object. You can call it on the class, as inPlayer.how_many(), without creating a player.- Write
Player.count += 1, notself.count += 1. The second one creates a new instance variable on that one object, and the shared counter stays at 0.
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.