Sub topic 3
Instance attributes and class attributes
This chapter assumes you can write a class with __init__ and self, and that you know lists and dictionaries. It covers where an attribute is stored, how Python finds it, and why one common mistake causes shared state.
Two places to store data
An attribute is a name attached to an object. Python can store it in two places:
- An instance attribute belongs to one object. You usually create it in
__init__withself.name = .... - A class attribute belongs to the class. You define it in the class body, outside any method. Every instance can read it.
class Dog:
species = "Canis familiaris" # class attribute shared by all dogs
def __init__(self, name, age):
self.name = name # instance attributes
self.age = age
def describe(self):
return f"{self.name} is {self.age} years old"
rex = Dog("Rex", 3)
print(rex.describe()) # Rex is 3 years old
print(rex.species) # Canis familiarisUse class attributes for constants and defaults that are the same for every instance. Use instance attributes for anything that differs between objects.
How lookup works
When you read obj.attr, Python checks the instance's own __dict__ first. If the name is missing there, it checks the class, then the parent classes in method resolution order.
Reads search upward, but writes do not. obj.attr = value always stores into the instance, even when a class attribute with the same name exists. The new instance attribute shadows the class attribute for that object only.
a = Dog("Rex", 3)
b = Dog("Fido", 5)
a.species = "Wolf" # creates an instance attribute on a
print(a.species) # Wolf
print(b.species) # Canis familiaris
print(Dog.species) # Canis familiaris
del a.species # remove the shadowing attribute
print(a.species) # Canis familiarisTo change the value for every instance, assign through the class: Dog.species = "...".
Gotcha: augmented assignment
self.count += 1 expands to self.count = self.count + 1. The right side reads the class attribute. The left side writes an instance attribute.
class Counter:
count = 0
def bump(self):
self.count += 1
c = Counter()
c.bump()
print(c.count) # 1
print(Counter.count) # 0, the class attribute never changedIf you want a counter shared by all instances, write Counter.count += 1, or type(self).count += 1 so subclasses work too.
Gotcha: mutable class attributes
The shadowing rule protects you when you assign. It does not protect you when you mutate. A call such as self.items.append(...) only reads items, so it finds the class's list and changes it in place.
class Basket:
items = [] # shared by every instance: a common bug
def add(self, item):
self.items.append(item)
class FixedBasket:
def __init__(self):
self.items = [] # a new list for each instance
def add(self, item):
self.items.append(item)
a, b = Basket(), Basket()
a.add("apple")
print(b.items) # ['apple']
c, d = FixedBasket(), FixedBasket()
c.add("apple")
print(d.items) # []Inspecting where a name lives
Compare vars(obj) with vars(type(obj)) to see where an attribute is stored.
rex = Dog("Rex", 3)
print(vars(rex)) # {'name': 'Rex', 'age': 3}
print("species" in vars(rex)) # False
print("species" in vars(Dog)) # True| Question | Instance attribute | Class attribute |
|---|---|---|
| Where is it defined? | `self.x = ...` in a method | In the class body |
| Where is it stored? | The instance `__dict__` | The class `__dict__` |
| Is it shared? | No | Yes, until an instance shadows it |
| Typical use | Per-object state | Constants, defaults, counters |
Exercise
A class defines tags = [] in its body, and add_tag(self, t) runs self.tags = self.tags + [t]. Do two instances share their tags after each calls add_tag? Explain why.
Show answer
No. The expression self.tags + [t] builds a new list, and the assignment self.tags = ... stores it as an instance attribute that shadows the class list. The class list is never modified. Using self.tags.append(t) instead would mutate the shared class list and leak tags between instances.