All sample questions / Python

Python Classes, Objects and Special Methods, what does print(l.x, l.y) print after class Lazy?

Block 3, Classes, Objects and Special Methods, question 5 of the Python sample

class Lazy:
    def __getattr__(self, name):
        return f'missing:{name}'

l = Lazy()
l.x = 1
print(l.x, l.y)

What does this print?

  1. A. 1 1
  2. B. 1 missing:y
  3. C. AttributeError
  4. D. missing:x missing:y
Show the answer and why each option is right or wrong

Answer, B. 1 missing:y

A. 1 1
Assumes the fallback method also somehow affects the value of x, making both reads return the same number. x was assigned the value 1 directly and is read back unchanged, y is the only name missing from the instance.
B. 1 missing:y
Correct. __getattr__ only runs for attributes that normal lookup fails to find, so the explicitly set x is returned directly and only y triggers the fallback.
C. AttributeError
Assumes accessing an attribute that does not exist on the instance always raises, even when __getattr__ is defined. Defining __getattr__ specifically replaces the usual AttributeError with whatever the method decides to return.
D. missing:x missing:y
Assumes __getattr__ intercepts every attribute access, even ones that were explicitly set. __getattr__ only fires when normal lookup fails to find the attribute, x was set directly on the instance so it is found without ever calling __getattr__.

__getattr__ is only called as a fallback, after Python has already checked the instance dictionary and the class hierarchy and found nothing. Attributes that already exist, like an explicitly assigned x, are returned by normal lookup and never reach __getattr__ at all.

The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 Python questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free Python sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.