Class vs. Instance
Attributes
Understand how Python objects share data through class attributes and hold unique data through instance attributes: the foundation of object-oriented design.
What Are Attributes?
In Python, an attribute is any variable attached to an object or class. Think of attributes as named slots that store data. Every time you write dog.name or Dog.species, you are accessing an attribute.
The Blueprint vs. the House
Why Does This Matter?
Choosing the right type of attribute affects memory usage, data consistency, and bug frequency. A single misplaced attribute can cause every object in your program to share data you intended to be private.
The Core Rule
Python's Lookup Chain
Class vs. Instance: Side by Side
| Class Attribute | Instance Attribute | |
|---|---|---|
| Where defined | In the class body | In __init__ via self |
| Ownership | Belongs to the class | Belongs to each object |
| Shared? | Yes: all instances | No: unique per object |
| Access via | ClassName.attr or obj.attr | obj.attr only |
| Use case | Constants, counters, defaults | Object-specific data |
How to Choose the Right Type
Example 1: Instance Counter
Example 2: Shadowing a Class Attribute
Example 3: The Mutable Trap
The Correct Pattern
Memory Model
When to Use Class vs. Instance
Counters: count = 0
Default configs: debug = False
Class-level metadata
State: self.score
Mutable collections: self.items = []
Per-object configuration
Common Mistakes
Quick Reference Summary
| Question | Answer |
|---|---|
| Where are class attrs stored? | In the class's __dict__ |
| Where are instance attrs stored? | In the object's __dict__ |
| What does assignment on an instance do? | Creates/updates an instance attribute (shadows class attr) |
| Are mutable class attrs safe? | No: shared reference causes bugs |
| How to modify a class attr properly? | Use ClassName.attr = value |
Question 1 of 5
Which of the following is a class attribute?
Question 2 of 5
Given the code below, what does print(b.x) output?
Question 3 of 5
Why is defining members = [] as a class attribute dangerous?
Question 4 of 5
To properly increment a class-level counter inside __init__, you should write:
Question 5 of 5
What happens when Python looks up obj.x and x is not in the instance's __dict__?