MiddleCodeCommonNot answered yet
What does this class-attribute shadowing print?
Predict all three lines.
class Parent: x = 1
class Child(Parent): pass
print(Parent.x, Child.x) # (1)
Child.x = 2
print(Parent.x, Child.x) # (2)
Parent.x = 3
print(Parent.x, Child.x) # (3)
Determine the output and explain.
1 1, then 1 2, then 3 2. Initially Child.x is inherited from Parent. Assigning Child.x = 2 creates a separate attribute on Child that shadows the parent's, so later changing Parent.x to 3 no longer affects Child, which keeps its own 2.
- ✗Thinking parent and child always share one attribute
- ✗Believing an attribute write propagates up the MRO to the parent
- ✗Expecting the child's shadow to clear when the parent is reassigned
- →Where does attribute lookup search, and in what order, along the MRO?
- →How does this differ for a mutable class attribute like a list?