Python Instance and Class Variables
This is the most asked subject in PCAP's 34% object-oriented section, and it comes down to one rule: reading an attribute searches the instance and then the class; assigning one always writes to the instance. Everything surprising follows - the list shared between every instance, and the counter that increments to 1 three times over.
Object-Oriented Python Guide 15 of 25 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 17 min
Unchanged in Python 3. The attribute lookup order described here is the same mechanism that makes inheritance work - see guide 18.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this because this is the most asked subject in PCAP's 34% object-oriented section. This matters because assigning through an instance creates an instance variable - so a mutable class variable is shared by every object, and a counter written the obvious way does not count.
- seeing where each kind of variable actually lives
- learning the rule the whole subject turns on, about assigning through an instance
- meeting the mutable class variable trap, and the fix
- finding what a class variable is really for, and the counter that does not count
- reading the whole rule in one line
Before you start
-
Where each variable lives
-
Assigning through an instance creates an instance variable
-
The trap: a mutable class variable
-
The fix
-
What a class variable is actually for
-
The counter that does not count
-
The rule, in one line
-
What the exam does with this objective