Python Shared Class Attributes
A class attribute is an attribute written on the class. Every instance shares it, while __init__ sets attributes for one instance only.
One value for all dogs
species sits on the class. Both dogs show the same species, with different names.
class Dog:
species = "dog"
def __init__(self, name):
self.name = name
rex = Dog("Rex")
bella = Dog("Bella")
print(rex.species)
print(bella.species)
print(rex.name)
print(bella.name)Change the shared value
Dog.species changes the class value. Both dogs show the new value at once.
class Dog:
species = "dog"
def __init__(self, name):
self.name = name
rex = Dog("Rex")
bella = Dog("Bella")
Dog.species = "canine"
print(rex.species)
print(bella.species)Change one instance only
rex.name changes one dog. Bella keeps her own name.
class Dog:
species = "dog"
def __init__(self, name):
self.name = name
rex = Dog("Rex")
bella = Dog("Bella")
rex.name = "Max"
print(rex.name)
print(bella.name)Example
class Player:
count = 0
team = "Red"
def __init__(self, name):
self.name = name
Player.count = Player.count + 1
a = Player("Ada")
b = Player("Bob")
print(Player.count)
print(a.team)
print(b.team)
print(a.name)
print(b.name)Key points
- Class attribute: an attribute written on the class, shared by all instances
- Use ClassName.name to read a class attribute
- Use self.name in __init__ to set an attribute for one instance
- Changing a class attribute changes it for every instance
- Changing an instance attribute changes it for that instance only
- A class attribute suits a value that never differs between instances
In this example, count and team sit on the Player class. Each __init__ call adds one to Player.count. Two players are built, so the count is 2. Both players show the shared team Red, while each keeps a different name.
Note
self.name reads the class value when the instance has no value of its own.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Two Dog objects share species = "dog". What happens after Dog.species = "canine"?