Search⌘ K
AI Features

Puzzle 12: Explanation

Explore how Python manages attribute access through __getattr__ and __getattribute__, understand the risks of infinite recursion, and learn the safest ways to modify attribute access using these hooks to improve your code's robustness.

We'll cover the following...

Let’s try it!

Try executing the code below to verify the result:

Python 3.8
class Seeker:
def __getattribute__(self, name):
if name not in self.__dict__:
return '<not found>'
return self.__dict__[name]
s = Seeker()
print(s.id)

Explanation

When we write s.id, Python does an attribute lookup (see Puzzle 1: Ready Player One). Python defines several hooks that bypass the usual attribute lookup algorithm. The two main ...