Sub topic 2
Review: class attributes versus instance attributes
This chapter reviews how Python stores data on a class and on its instances. Class methods, which come next, work with the class-level data described here.
Prerequisites
This chapter assumes you can already:
- Define a class and write instance methods that take
self. - Set instance attributes in
__init__. - Read
@namedecorator syntax above a function. You don't need to write decorators yourself.
Two places to store data
An instance attribute belongs to one object. You usually create it by assigning to self inside __init__. A class attribute belongs to the class object itself. You create it by assigning in the class body, outside any method.
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name):
self.name = name # instance attribute
rex = Dog("Rex")
fido = Dog("Fido")
print(rex.name, fido.name) # Rex Fido
print(rex.species, fido.species) # Canis familiaris Canis familiaris
print(Dog.species) # Canis familiarisEach dog has its own name. Both dogs read the same species from Dog, and you can also read it through the class without creating any instance.
How attribute lookup works
When you write obj.attr, Python searches in a fixed order:
- The instance's own
__dict__. - The class of the instance.
- The parent classes, in method resolution order.
The first match wins. If nothing matches, Python raises AttributeError.
flowchart TDThe diagram below shows this search.
Lookup order has an important consequence for reading and writing. Reading can fall through to the class. Writing through an instance never does.
Assignment through an instance shadows the class attribute
Assigning to obj.attr always stores the value in the instance's __dict__. It never changes the class attribute. The new instance attribute then shadows (hides) the class attribute for that one object.
class Dog:
species = "Canis familiaris"
a = Dog()
b = Dog()
a.species = "Canis lupus"
print(a.species) # Canis lupus
print(b.species) # Canis familiaris
print(Dog.species) # Canis familiaris
print(a.__dict__) # {'species': 'Canis lupus'}To change the value for every instance that has not shadowed it, assign through the class: Dog.species = "...".
The counter trap
A common bug appears when you try to keep a count of instances.
class Counter:
count = 0
def __init__(self):
self.count += 1
Counter()
Counter()
print(Counter.count) # 0The line self.count += 1 expands to self.count = self.count + 1. The right side reads the class value, 0. The left side writes a new instance attribute, 1, on that one object. The class attribute never changes. The fix is to name the class explicitly:
class Counter:
count = 0
def __init__(self):
Counter.count += 1
Counter()
Counter()
print(Counter.count) # 2Hard-coding Counter works, but it has a cost with inheritance. Class methods give you a cleaner way to refer to "the current class", which later chapters cover.
Mutable class attributes are shared
Because all instances read the same class attribute, a mutable value such as a list or dict is shared. Calling a method that changes it in place, such as append, affects every instance. No assignment happens, so no shadowing occurs.
class Team:
members = [] # one list, shared by all teams
def add(self, name):
self.members.append(name)
red = Team()
blue = Team()
red.add("Ana")
print(blue.members) # ['Ana']
print(red.members is blue.members) # TrueIf each object needs its own list, create it in __init__:
class Team:
def __init__(self):
self.members = []
def add(self, name):
self.members.append(name)
red = Team()
blue = Team()
red.add("Ana")
print(blue.members) # []Which one to use
| Question | Use |
|---|---|
| Does each object need its own value? | Instance attribute |
| Is the value a constant or default shared by all objects? | Class attribute |
| Is it a running total across all objects? | Class attribute, updated through the class |
| Is it a list or dict that differs per object? | Instance attribute, created in `__init__` |
Why this matters for class methods
An instance method receives self, so it can reach instance data directly and class data through lookup. A class method receives the class instead, which makes it the natural place to read or update class attributes without needing an instance. Because it works through the class object, an update made there is a true class-level change, not a shadowing assignment like the one in the counter trap.
Exercise
Given the code below, what do the three print calls output, and why? class Light: color = "white" x = Light() y = Light() x.color = "red" Light.color = "blue" print(x.color) print(y.color) print(Light.color)
Show answer
The output is red, blue, blue. The assignment x.color = "red" creates an instance attribute on x that shadows the class attribute. The assignment Light.color = "blue" changes the class attribute. y has no color of its own, so it reads the new class value, blue. x still has its own value, red.
Exercise
A class Playlist has a class attribute songs = [] and a method add(self, title) that calls self.songs.append(title). Two playlists are created and one song is added to the first. What does the second playlist contain, and how do you fix the design?
Show answer
The second playlist also contains the song, because both instances share one list from the class. Fix it by removing the class attribute and writing self.songs = [] inside _init_, so each playlist gets its own list.