Skip to the solution
HardDSA11 min read

How does attribute lookup work on a Python object?

402 views

The problem

Question presented to candidate: "When you write obj.name in Python, where does the value actually come from? Walk me through the order Python checks things in, and explain why an instance attribute can hide a method but cannot hide a property."

What a strong answer should cover:

  • obj.name calls type(obj).__getattribute__(obj, "name"); for ordinary classes that is object.__getattribute__, and __getattr__ is called only if it raises AttributeError.
  • The precedence: a data descriptor found on the class (defines __set__ or __delete__, such as property) wins; then the instance __dict__; then a non-data descriptor or plain class attribute found by walking type(obj).__mro__; then __getattr__; else AttributeError.
  • Why methods can be shadowed: a function is a non-data descriptor (only __get__), so an instance-dict entry with the same name wins; property is a data descriptor, so it does not.
  • Assignment is different from reading: obj.x = v goes to a data descriptor's __set__ if one exists, otherwise straight into obj.__dict__ (which is why self.count += 1 on a class attribute creates an instance copy).
  • Implicit special-method lookups (len(obj), a + b) go to the type and skip the instance dict and __getattr__; __slots__ replaces the instance dict with descriptors on the class.

Clarifying questions expected:

  • Do you want normal instance lookup only, or also lookup on a class object (which uses type.__getattribute__ and the metaclass)?

Code / implementation expected: Optional β€” a small class showing a data descriptor beating the instance dict and the instance dict beating a method.

  • attributes
  • lookup

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThe lookup order, traced, plus a pure-Python model of it
PythonSpecial methods, properties, class attributes and __slots__

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 133 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

What is the descriptor protocol?

Continue