Python’s Attribute Lookup

The Puzzling Case of a Ghostly delorean

Miki Tebeka
The Pragmatic Programmers
3 min readMay 26, 2021

--

Rev those brains and get ready to solve a mystery involving Python, attribute lookups, and some fun code involving an infamous car.

Image by By Thiago Melo on Shutterstock

The Puzzle

Here’s a riddle for you — what will the following code print?

Try to guess before looking at the answer.

The Answer

If you’ll run this code, it’ll print 0. Why, Python? Why???

To see what’s going on, you’ll need to understand how Python is doing attribute lookup. Most Python objects store their attributes in a special dict called __dict__.

When you write Cars.num_cars or delorean.num_cars Python does the following algorithm:

  • First look at the object __dict__
  • Then look at the object class __dict__
  • Then go up the inheritance tree and search for the attribute in the __dict__ of each class
  • Finally, if it can’t find the attribute, raise…

--

--