bhylu.com

Advertisements

Magic Methods

Special methods connect an object to Python's built-in protocols. Define them when the operation has a natural, predictable meaning for your type.

Understand the idea

Methods such as __len__, __str__, and __contains__ are normally reached through len, str, and in. The protocol has return-type expectations; for example, __len__ must produce a non-negative integer. Do not add every possible special method. A small honest interface is better than surprising arithmetic or equality for an object.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Roster:
    def __init__(self, names):
        self.names = list(names)
    def __len__(self):
        return len(self.names)

print(len(Roster(["Mira", "Dev"])))

Read the result

The output is 2 through the length protocol.

Try one change

Add __contains__ for checking names and explain which internal collection it should consult.