Classes and OOP II

Magic Methods

You wrote __str__ in OOP I to control what print() shows. Python has a whole family of these dunder methods. They let your objects work with ==, +, and len().


You wrote __str__ in OOP I to control what print() shows. There is a whole family of these dunder methods that hook your objects into Python operators and built-in functions.

Without a custom dunder the default repr just shows the type and memory address — not very useful:

Python

__repr__ is the developer-facing version of __str__. It is what you see in the REPL or when an object appears inside a list.

Without __repr__ you get the default ugly form. With it, you control the output:

Python
Output

What will be the output?

Python

__eq__ controls what == means for your class. By default two objects are equal only if they are the same instance.

Two coins with the same value should compare equal. Define __eq__ to make that happen:

Python
Output

What will be the output?

Python

__add__ teaches Python what + means for your class. The result is whatever the method returns.

Adding two vectors returns a new Vector with summed parts:

Python
Output

What will be the output?

Python

__len__ tells the built-in len() what to return for your object. It must return an integer.

A Playlist holds a list of songs. len() reports how many:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python