Lesson · Object-Oriented Python
Instance vs Class Attributes
55 min readInstance vs Class Attributes
Instance attributes belong to one object, while class attributes live on the class and are shared through attribute lookup. Confusing the two is a common source of accidental shared state.
Learning goals
- Explain where
self.value = 0stores its data and whya.value = 10does not affectb. - Read
Counter.instances += 1and say why the class is named explicitly instead of writingself.instances += 1. - Trace attribute lookup order: the instance dictionary first, then the class and its bases.
- Predict when an assignment on an instance creates per-instance data that shadows a class value.
- Choose between a class-level constant and an instance attribute for a given piece of shared or per-object data.
Mental model
The same path explains the two storage locations: self.value = 0 lands in the instance dictionary so each object gets its own slot, while instances = 0 in the class body lands in the class namespace that every instance can read. Assignment decides where data lives; lookup decides what you see.
Mental model
read it top to bottom
read a.value ↓ search the instance dictionary (a.__dict__) first found? return it (a.value = 10 wrote here) ↓ not found walk the class and its bases (type(a).__mro__) ↓ still not found AttributeError
Core idea
The split is about ownership: data written in the class body is shared by every instance that never overrides it, and data written through self belongs to one object. Attribute lookup reads the instance dictionary first and falls back to the class, so a per-instance assignment silently shadows a class value instead of changing it. Name the class explicitly, as in Counter.instances += 1, whenever an operation must update shared state.
Instance attributes
Instance attributes are stored in the instance's own dictionary (or its slots) and belong to that object alone. self.value = 0 in Counter.__init__ creates one slot per instance, so a.value = 10 leaves b.value at 0. Assignment on an instance always writes the instance namespace, never the class.
Class attributes
Class attributes are defined in the class body and shared by every instance that does not override them; instances = 0 lives on Counter itself. Reading self.instances finds the class value through lookup, but assignment through self would create an instance attribute that shadows it. Mutations that must affect all instances have to target the class, as in Counter.instances += 1.
Attribute lookup
Instance attribute access consults descriptors, the instance dictionary, and class hierarchy according to specific precedence rules. Understanding that order explains properties, methods, and shadowing.
Shared mutable class attribute trap
A mutable class attribute is shared by every instance that reads it through the class. Use an instance attribute when each object needs independent mutable state.
Class-level constants
A class-level constant communicates data shared by all instances. Python does not enforce immutability, so naming and type hints such as Final can express the intent.
Walkthrough
instances = 0sits in the class body, so it is stored on theCounterclass itself and every instance sees it through lookup.Counter.instances += 1in__init__reads the class attribute, adds one, and writes it back to the class;self.instances += 1instead would create a per-instance shadow and the class counter would stay at 0.self.value = 0bindsvaluein each instance's own dictionary, so aftera.value = 10the two objects hold independent values andprint(a.value, b.value)shows10 0.- Predict before running: what
print(Counter.instances)shows after two constructions, and whatCounter.valueraises, sincevaluewas only ever written throughself.
Experiments to try
- Print
a.__dict__andb.__dict__after the example; note thatinstancesnever appears in either one and say where it lives instead. - Replace
Counter.instances += 1withself.instances += 1and run again; explain the new output and where eachinstancesname ended up. - Give
Counterahistory = []class attribute, append throughself.historyin__init__, and observe both instances sharing one list; repair it by assigning a fresh list throughself. - Read
Counter.__dict__and compare it witha.__dict__to draw the exact boundary between the two namespaces.
Common mistakes
- Writing
self.instances += 1for a shared counter: the augmented assignment creates an instance attribute, so each object counts itself while the class value stays at 0. - Storing a mutable class attribute such as
history = []and appending to it per instance: every instance mutates the same list, so data leaks between objects. - Assuming
a.value = 10changes the class or other instances: assignment always writes the instance dictionary, sob.valuekeeps its own value. - Expecting class-attribute mutation through an instance to be visible on the class:
a.instances = 99shadows the class name, and onlyCounter.instances = 99changes the shared value.
Practice: Easy
- Run the worked example, then print
a.__dict__andb.__dict__. Point at the exact line that putvalueinto each dictionary and explain whyinstancesis missing from both. - Change the example by adding
Counter.value = 10before the final print, and predict whatprint(a.value, b.value)shows before you run it. Explain the result with lookup order. - Create a third counter
c = Counter()and print all threevalueattributes plusCounter.instances; confirm which numbers are shared and which are per instance.
Practice: Medium
- Add a
reset_value(self)method that setsself.value = 0, and areset_class(cls)classmethod that setscls.instances = 0. For each, state which namespace the assignment targets, then test calling them on one instance and on the class. - Reproduce the shared mutable class attribute trap with
history = []and an__init__that appends. Fix it so each instance gets its own list while the class-level default stays readable. - Read
Counter.__mro__and write one sentence describing the order lookup follows for a name that exists only on a base class.
Practice: Hard
- Design a
Ticketclass where each instance carries a unique sequential number while the class tracksissuedand a shared price table. Specify which data is class-level, which is per instance, and how the counter stays correct if construction fails midway. - Build a failure lab around two traps: a shared mutable class attribute mutated through
self, and a counter incremented withself.counter += 1. Show the wrong output, name the mechanism, then apply the repair. - Connect this lesson to the properties lesson: replace a plain
valueattribute with a read-only property backed by_value, then explain what changes for lookup and for assignment through the instance.
Lesson checklist
- I can point to the namespace that receives
self.value = 0and the one that receivesinstances = 0. - I can explain why
a.value = 10leavesb.valueand the class untouched. - I can say where the write happens in
Counter.instances += 1and why the class is named explicitly. - I can spot a shared mutable class attribute and repair it with per-instance state.
Remember
Instance attributes live in each object's dictionary, class attributes live in the class namespace, and lookup walks from the instance to the class and its bases. The trap is ownership: `self.instances += 1` shadows the class counter, and a mutable class attribute is one list shared by every instance, so shared state must be written through the class name.
Interview angles
What is the main purpose of **Instance attributes**?+
Instance attributes are stored in the instance's own dictionary (or its slots) and belong to that object alone. self.value = 0 in Counter.__init__ creates one slot per instance, so a.value = 10 leaves b.value at 0. Assignment on an instance always writes the instance namespace, never the class.
What should you pay attention to when using **Class attributes**?+
Class attributes are defined in the class body and shared by every instance that does not override them; instances = 0 lives on Counter itself. Reading self.instances finds the class value through lookup, but assignment through self would create an instance attribute that shadows it. Mutations that must affect all instances have to target the class, as in Counter.instances += 1.
How does **Attribute lookup** fit into this lesson?+
Instance attribute access consults descriptors, the instance dictionary, and class hierarchy according to specific precedence rules. Understanding that order explains properties, methods, and shadowing.
Why does `self.instances += 1` fail to update a class-level counter?+
An augmented assignment through self reads the class value but writes back into the instance dictionary, creating a per-instance shadow; the class attribute keeps its old value. Shared updates must name the class, as in Counter.instances += 1.