Attribute Shadowing occurs when:
👉 An instance variable has the same name as a class variable.
Result:
✔ Instance variable overrides class variable
✔ Class variable remains unchanged
Python attribute lookup order:
1. Object Namespace (Highest Priority)
2. Class Namespace
3. Parent Classes
Instance namespace always wins.
class Demo:
value = 10d = Demo()
print(d.value)Output:
10
✔ Found in class namespace
Assign same attribute via instance:
d.value = 99print(d.value)
print(Demo.value)Output:
99
10
Python created:
✔ NEW variable inside object namespace
print(d.__dict__)Output:
{'value': 99}
✔ Class variable untouched
Assignment via object NEVER modifies class variable
It creates a new instance variable instead.
Because Python lookup prioritizes:
👉 Instance → Class
This enables:
✔ Object-specific overrides
✔ Flexible object behavior
✔ Dynamic customization
Before shadowing:
Class Namespace → value = 10
Object Namespace → empty
After:
Class Namespace → value = 10
Object Namespace → value = 99
Lookup:
object.value → finds instance first → 99
Shadowing ≠ Mutation
d.value = 99Demo.value = 99Affects all instances.
class Person:
hobbies = []p1 = Person()
p2 = Person()
p1.hobbies.append("Coding")
print(p2.hobbies)Output:
['Coding']
WHY?
Because:
✔ No shadowing happened
✔ Lookup found class variable
✔ Mutation modified shared object
p1.hobbies = []Now:
✔ Instance variable created
✔ Shadowing activated
Methods are class attributes.
class Demo:
def greet(self):
print("Hello")d = Demo()
d.greet = "Not a method anymore"
print(d.greet)Method shadowed!
✔ Breaks object behavior
✔ Confusing debugging
✔ Silent logical errors
print(d.__dict__) # Instance namespace
print(Demo.__dict__) # Class namespace| Concept | Meaning |
|---|---|
| Shadowing | Instance hides class attribute |
| Overriding | Child class redefines parent method |
| Confusion | Reality |
|---|---|
| Instance modified class variable | ❌ No |
| Shadowing deletes class variable | ❌ No |
| Shadowing = mutation | ❌ |
| Shadowing always bad | ❌ Sometimes intentional |
| Methods immune to shadowing | ❌ No |
✔ Temporary overrides
✔ Object-specific behavior
✔ Testing / mocking
✔ Dynamic configurations
Example:
obj.timeout = 5✔ Accidental attribute naming
✔ Mutable shared state
✔ Method replacement
✔ Debugging nightmares
✔ Avoid naming collisions
✔ Use instance variables carefully
✔ Never shadow methods unintentionally
✔ Avoid mutable class variables
✔ Understand lookup order
| Concept | Truth |
|---|---|
| Shadowing | Instance overrides class lookup |
| Lookup Order | Instance → Class |
| Mutation | Changes shared object |
| Assignment via object | Creates instance variable |
| Class variable unchanged | ✅ Yes |
| Methods can be shadowed | 🚨 Yes |
- Create shadowing examples
- Print instance vs class namespaces
- Shadow a method intentionally
- Trigger mutable class variable bug
- Predict outputs before execution
- Compare mutation vs shadowing
- Create debugging scenario