Puzzle 1 Ready Player One

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Part 1 Python Brain Teasers | TOC | A Slice of π 👉

player.py

​ ​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)

Guess the Output

IMPORTANT

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

images/hline.png

This code will print: 0

images/hline.png

When you write self.count, you’re doing an attribute lookup. The attribute you’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 the instance’s class (__class__) dictionary, and then up the inheritance hierarchy (__mro__). Finally, if the attribute you’re looking for is not found, Python will raise an AttributeError.

--

--

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.