Object-Oriented Programming
Instance Variables
Object-specific data and attribute management
Interview: Tests understanding of object state, __dict__, __slots__, and dynamic attribute behavior
Instance variables are data attributes that belong to a specific object (instance). Each object maintains its own copy of instance variables, making them essential for storing per-object state. Understanding instance variables deeply is key to mastering Python's object model.
How Instance Variables Work
- Defined inside methods (usually
__init__) usingself.attribute_name - Each instance has its own independent copy of instance variables
- Stored in the object's
__dict__(a dictionary mapping names to values) - Can be added, modified, or deleted dynamically at runtime
- Accessed via dot notation:
obj.attributeorgetattr(obj, 'attribute')
Dynamic Attributes
Unlike many statically-typed languages, Python allows you to add attributes to objects at any time. This flexibility is powerful but can lead to bugs if not managed carefully. Use __slots__ to prevent dynamic attribute creation when you want strict control.
__slots__ for Memory Optimization
When you define __slots__, Python replaces the instance's __dict__ with a fixed-size array, significantly reducing memory usage. This is especially important when creating millions of objects.
Common Pitfall
Adding attributes dynamically to one instance does NOT add them to other instances or the class. This can lead to AttributeError when you iterate over objects and some are missing attributes.
Use Cases
Storing per-object state like counters, flags, and configuration
Building data models where each record has unique values
Game development: each entity has position, health, inventory
Using __slots__ for memory-efficient classes with millions of instances
Dynamic attribute assignment for flexible data processing
Common Mistakes
Assuming all instances have the same attributes — dynamic attributes can differ per object
Forgetting that __slots__ removes __dict__, breaking setattr and some libraries
Not using __slots__ when creating millions of objects (wastes memory)
Confusing instance variables with class variables when using mutable defaults
Accessing instance variables before __init__ sets them causes AttributeError