Sub topic 2
Review: Class Attributes Versus Instance Attributes
What this chapter assumes
This chapter reviews one idea that the rest of the tutorial depends on: where Python stores data and how it finds it again. You should already be comfortable with these points:
- You can define a class, write
__init__, and create instances. - You know that
selfis the instance a method was called on. - You have seen the
@namedecorator syntax above a function.
Class methods and static methods are attributes of the class, not of any one instance. If the difference between the two kinds of attribute is fuzzy, cls will be fuzzy too. After this chapter you should be able to predict what Python reads and what it writes in each of the cases below.
Two places to store data
Every Python object has its own namespace, which is a dictionary of names to values. Instances and classes are both objects, so each has one:
- An instance attribute is stored in the instance's namespace, usually through
self.name = value. Each instance has its own copy. - A class attribute is stored in the class's namespace, by assigning a name in the class body or through the class (
ClassName.name = value). All instances share it.
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) # Rex
print(fido.name) # Fido
print(rex.species) # Canis familiaris
print(Dog.species) # Canis familiaris
print(rex.__dict__) # {'name': 'Rex'}
print("species" in Dog.__dict__) # Truespecies appears in Dog.__dict__ and not in rex.__dict__. The instance does not hold a copy. When you write rex.species, Python finds the value by searching, as the next section describes.
The __dict__ attribute is a debugging aid. When you are unsure where a value lives, print obj.__dict__ and type(obj).__dict__ (or call vars(obj)).
How lookup works
When you read obj.name, Python searches in a fixed order and stops at the first match:
- The instance's own namespace (
obj.__dict__). - The class of the instance.
- The parent classes, in method resolution order (MRO). The MRO is the linear order Python derives from the inheritance graph. You can print it with
ClassName.__mro__.
If nothing matches, Python raises AttributeError.
Methods follow the same search. A method is a function stored as a class attribute:
class Dog:
def speak(self):
return "Woof"
rex = Dog()
print("speak" in Dog.__dict__) # True
print("speak" in rex.__dict__) # False
print(rex.speak()) # WoofThis is why the topic belongs in this tutorial. @classmethod and @staticmethod are two more kinds of object stored in the class namespace, and they differ in what happens at lookup time. The last chapter covers that mechanism.
Reading is shared, assigning is not
The search order applies to reads only. An assignment such as obj.name = value always writes to the namespace of the object on the left, which is obj. It never changes the class, even if the class already has an attribute with that name.
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
rex = Dog("Rex")
fido = Dog("Fido")
rex.species = "Canis lupus" # creates an instance attribute on rex
print(rex.species) # Canis lupus
print(fido.species) # Canis familiaris
print(Dog.species) # Canis familiaris
print(rex.__dict__) # {'name': 'Rex', 'species': 'Canis lupus'}
del rex.species # remove the instance attribute
print(rex.species) # Canis familiarisThe assignment gave rex its own species. This is called shadowing: the instance attribute hides the class attribute of the same name for that instance only. Deleting the instance attribute makes the class attribute visible again.
To change the value for every instance that has not shadowed it, assign through the class:
class Dog:
species = "Canis familiaris"
rex = Dog()
fido = Dog()
Dog.species = "Canis lupus familiaris"
print(rex.species) # Canis lupus familiaris
print(fido.species) # Canis lupus familiarisBoth instances see the change because neither has its own species. If rex had shadowed the name earlier, it would keep its own value.
| Expression | What Python does |
|---|---|
| `obj.x` (read) | Searches instance, then class, then parents |
| `obj.x = 1` (write) | Stores `x` in the instance namespace |
| `Cls.x` (read) | Searches the class, then parents |
| `Cls.x = 1` (write) | Stores `x` in the class namespace |
| `del obj.x` | Removes `x` from the instance namespace only |
Pitfall: mutable class attributes
Because a read finds the shared class attribute, calling a mutating method on it changes the one object everyone shares. Mutating is not assigning, so no shadowing occurs.
class Basket:
items = [] # one list, shared by every Basket
def add(self, item):
self.items.append(item) # reads self.items, mutates the shared list
a = Basket()
b = Basket()
a.add("apple")
print(b.items) # ['apple']
print(a.items is b.items) # Trueself.items.append(item) reads self.items, which finds the class list. It then calls append on that list. Nothing is assigned to self, so a never gets an instance attribute.
The usual fix is to create the list per instance in __init__:
class Basket:
def __init__(self):
self.items = [] # a new list for each instance
def add(self, item):
self.items.append(item)
a = Basket()
b = Basket()
a.add("apple")
print(a.items) # ['apple']
print(b.items) # []A mutable class attribute is correct when you want shared state, for example a registry of all subclasses. The problem is sharing by accident. Immutable values such as numbers, strings, and tuples are safe as class-level defaults, because you cannot change them in place. You can only rebind the name.
Pitfall: augmented assignment on a class attribute
The operator += combines a read and a write. For an immutable value, the read finds the class attribute, but the write goes to the instance.
class Counter:
count = 0
def hit(self):
self.count += 1 # means: self.count = self.count + 1
c1 = Counter()
c1.hit()
c1.hit()
print(c1.count) # 2
print(Counter.count) # 0
print(c1.__dict__) # {'count': 2}The first hit reads 0 from the class, adds 1, and stores 1 on the instance. From then on the instance shadows the class value. If you meant to count across all instances, self.count += 1 is a bug that does not raise an error.
To update the shared value, write through the class:
class Widget:
created = 0
def __init__(self):
Widget.created += 1
Widget()
Widget()
print(Widget.created) # 2This works, but it writes the class name inside the method. That has a cost under inheritance, which the next section shows.
Class attributes and subclasses
Subclasses inherit class attributes through the MRO. A subclass can override one by defining the same name in its own body. Assigning through a subclass also creates a new attribute on that subclass, and the parent is unchanged.
class Vehicle:
wheels = 4
class Motorcycle(Vehicle):
wheels = 2
class Truck(Vehicle):
pass
print(Vehicle.wheels) # 4
print(Motorcycle.wheels) # 2
print(Truck.wheels) # 4 (inherited)
Truck.wheels = 6
print(Truck.wheels) # 6
print(Vehicle.wheels) # 4This matters for a counter that uses type(self) instead of a fixed class name:
class Widget:
created = 0
def __init__(self):
type(self).created += 1
class Gadget(Widget):
pass
Widget()
Gadget()
Gadget()
print(Widget.created) # 1
print(Gadget.created) # 3The first Gadget() reads created through Gadget. The attribute is not on Gadget yet, so it finds Widget.created, which is 1. It adds 1 and stores 2 on Gadget. From then on Gadget has its own counter, which reaches 3, and Widget.created stays at 1. The totals are split, and the split starts at an unpredictable point.
Neither version, Widget.created += 1 or type(self).created += 1, always gives the result you want. Both are reasonable, but each makes a different choice:
Widget.created += 1keeps one counter for the whole hierarchy.type(self).created += 1ends up with a separate counter for each subclass that is instantiated, but only after the first write, and its starting value is inherited.
Choose on purpose and document the choice. Later chapters use class methods to make this kind of decision explicit.
Class attributes on the class versus through an instance
You can read a class attribute through an instance, which is convenient. For clarity, many teams follow a convention:
- Use
ClassName.attrortype(self).attrwhen you mean the shared value. - Use
self.attrwhen you mean this instance's value, or when you want subclass and instance overrides to apply.
Reading through self is a deliberate feature when you want per-instance overrides:
class Report:
title = "Untitled"
def header(self):
return f"== {self.title} =="
class SalesReport(Report):
title = "Sales"
special = Report()
special.title = "One-off"
print(Report().header()) # == Untitled ==
print(SalesReport().header()) # == Sales ==
print(special.header()) # == One-off ==One method, three behaviors. The class attribute is the default, a subclass overrides it, and an instance overrides it again.
Descriptors take priority over instance attributes
The lookup order above is accurate for plain values. One exception is worth knowing now. If the class attribute is a data descriptor, such as a property, it wins over the instance dictionary. A data descriptor is an object that defines __set__ or __delete__ as well as __get__.
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
c = Circle(3)
try:
c.radius = 5
except AttributeError as error:
print("blocked:", type(error).__name__) # blocked: AttributeErrorThe assignment did not create an instance attribute. It reached the property on the class, which has no setter. Functions are non-data descriptors. They only define __get__, so an instance attribute can shadow a method:
class Greeter:
def hello(self):
return "hello from class"
g = Greeter()
g.hello = lambda: "hello from instance"
print(g.hello()) # hello from instance
print(Greeter().hello()) # hello from classYou will rarely do this on purpose. It explains why @classmethod and @staticmethod work. They are descriptors that decide what a method receives when it is looked up on a class or an instance, and the final chapter explains how.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Instances unexpectedly share a list or dict | Mutable value defined in the class body | Create it in `__init__` as `self.x = []` |
| Class counter stays at 0 | `self.count += 1` writes to the instance | Write through the class: `Cls.count += 1` |
| Changing `Cls.x` does not affect one instance | That instance shadows `x` with its own value | `del obj.x`, or stop assigning to `obj.x` |
| Subclass counters drift apart | `type(self).n += 1` creates an attribute on the subclass | Decide whether the count is per hierarchy or per class, and write it that way |
| Assigning to a property raises `AttributeError` | The property has no setter | Define a setter, or assign to the underlying attribute |
| `AttributeError` for a name you defined | Defined as a local variable in `__init__` without `self.` | Use `self.name = ...` |
Exercises
Exercise
Given the code below, what does it print, and where does level live after each step?
class Player:
level = 1
p = Player()
q = Player()
p.level += 1
Player.level = 10
print(p.level, q.level, Player.level)
Show answer
It prints 2 10 10. The line p.level += 1 reads 1 from the class, adds 1, and stores 2 in p.__dict__, so p now shadows the class attribute. q has no instance attribute, so q.level reads the class value. After Player.level = 10 assigns through the class, q.level and Player.level are both 10, while p.level stays at its own 2.
Exercise
This class is meant to give each team its own member list, but all teams share one list. Explain why, and fix it. class Team: members = [] def join(self, name): self.members.append(name)
Show answer
members is defined in the class body, so every instance reads the same list, and append mutates it in place without assigning to self. No instance attribute is ever created. Fix it by creating the list per instance: add def __init__(self): self.members = [] and keep join unchanged.
Exercise
You want to count how many Ticket objects have been created across the whole program, including objects of subclasses of Ticket. Write the __init__ line that increments the counter, and say why type(self).total += 1 would not do the job.
Show answer
Use Ticket.total += 1 with total = 0 defined in the Ticket class body. That always writes to the one shared counter. With type(self).total += 1, the first instantiation of a subclass reads the inherited value, then creates a new total on the subclass. From then on the subclass keeps a separate count, so Ticket.total no longer reflects those objects.
Exercise
How can you check, without reading the source, whether unit is stored on an instance m or inherited from its class?
Show answer
Check the namespaces directly. "unit" in m.__dict__ is True if the instance holds its own value. "unit" in type(m).__dict__ is True if the class defines it. If both are False, look at type(m).__mro__ and check each parent's __dict__.