Object-Oriented Programming
Class Variables
Shared class-level data and shadowing behavior
Interview: Frequently tested — interviewers ask about class variable shadowing, mutable class variables, and class-level registries
Class variables are attributes defined at the class level, shared by all instances of that class. They're useful for constants, counters, registries, and default values. However, the shadowing behavior when accessing class variables through instances is a common source of bugs and a favorite interview topic.
Class Variables vs Instance Variables
- Class variables: Defined outside any method, at class body level
- Shared: All instances see the same value (unless shadowed)
- Access: Via
ClassName.variable(preferred) orinstance.variable - Modification: Use
ClassName.variable = valueto change for all instances
The Shadowing Problem
When you assign to instance.class_var, Python creates a new instance variable that shadows the class variable. The class variable remains unchanged, and other instances still see the original value. This is one of the most common OOP bugs in Python.
Class Variable Use Cases
- Instance counters (tracking how many objects were created)
- Constants shared across all instances (e.g.,
PI = 3.14159) - Registries (tracking all instances of a class)
- Default configuration values
Interview Tip
Be ready to explain what happens when you do obj.class_var = new_value — it creates an instance variable that shadows the class variable. Use ClassName.class_var = new_value to modify the shared value.
Use Cases
Tracking instance count (e.g., active connections, created objects)
Defining constants shared across instances (e.g., MAX_SIZE, DEFAULT_COLOR)
Building registries (plugin systems, handler maps)
Sharing configuration across all instances of a class
Implementing class-level caches and lookup tables
Common Mistakes
Accidentally shadowing class variables by assigning through an instance
Using mutable class variables (lists, dicts) — they are shared across ALL instances
Modifying class variable via instance instead of ClassName — creates shadow
Not understanding that class variables and instance variables live in different namespaces
Forgetting that subclasses inherit class variables but can shadow them independently