Attribute Lookup Chain — ELI5
Imagine you’re looking for your keys. You check your pockets first. Not there? You check your bag. Still not there? You check the kitchen counter. Then the hook by the door. You always search in the same order, and you stop as soon as you find them.
Python does the exact same thing when you write dog.name. It doesn’t magically know where name lives. It searches through a specific list of places, in order, and uses the first match it finds.
The Search Order
- The object itself — Did someone put
namedirectly on this specific dog? - The class — Did the
Dogclass definenamefor all dogs? - Parent classes — Did a parent class (like
Animal) definename?
If Python checks everywhere and finds nothing, it throws an error — like you giving up and saying “I can’t find my keys anywhere!”
Why Does This Matter?
Because the order determines what you get. If both the dog object AND the Dog class have something called name, you get the one from the object — because Python checks there first.
It’s like asking “What’s the rule?” You follow your own version first. Only if you don’t have one do you check what your family says. And only if your family doesn’t have one do you look at what society says.
A Surprise Twist
There’s actually a secret step that can jump the line: something called a descriptor. Think of it as a VIP that gets checked even before the object’s own stuff. Properties (the @property thing) are descriptors, and they can override what an object thinks it has.
One thing to remember: When you access obj.attr, Python searches in a specific order — and the first place it finds the attribute wins.
See Also
- Python Bytecode And Interpreter How your .py file turns into tiny instructions the Python interpreter can execute step by step.
- Python Class Body Execution Python runs the code inside your class definition immediately — like reading a recipe out loud before anyone starts cooking.
- Python Data Model Customization How Python lets your objects behave like built-in types — adding, comparing, looping, and printing, all with special methods.
- Python Garbage Collection See how Python cleans up unreachable objects, especially the tricky ones that point at each other.
- Python Gil Why Python threads can feel stuck in traffic, and how the GIL explains the behavior.