Search⌘ K
AI Features

Puzzle 1: Explanation

Explore Python's attribute lookup process by understanding how instance and class dictionaries interact. Learn how Python handles attribute retrieval and assignment, including the effects of modifying attributes at the instance level versus the class level.

Let’s try it!

Try executing the code below to verify the results:

Python 3.8
class Player:
# Number of players in the Game
count = 0
def __init__(self, name):
self.name = name
self.count += 1
p1 = Player('Parzival')
print(Player.count)

Code explanation

When we write self.count, we’re doing an attribute lookup. The attribute that we’re looking for in this case is count. Getting an attribute in Python is a complex operation. Almost every Python object stores its attributes in a dict called __dict__.

Python will first try to find the attribute in the instance dictionary, then in ...