Puzzle 12 Attention Seeker

Python Brain Teasers — by Miki Tebeka (21 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Click the Button | TOC | Identity Crisis 👉

seeker.py

​1: ​class​ Seeker:
​2: ​def​ ​__getattribute__​(self, name):
​3: ​if​ name ​not​ ​in​ self.__dict__:
​4: ​return​ ​'<not found>'​
​5: ​return​ self.__dict__[name]
​6:
​7:
​8: s = Seeker()
​9: ​print​(s.id)

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will raise a RecursionError exception.

images/hline.png

When you write s.id, Python does an attribute lookup (see puzzle 1, Puzzle 1, Ready Player One). Python defines several hooks to bypass the usual attribute lookup algorithm. The two main options are __getattr__ and __getattribute__.

Other Options

INFORMATION

There are several other ways to modify attribute access such as staticmethod, classmethod, properties, descriptors, and more.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.