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:
__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:
What will be the output?
__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:
What will be the output?
__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:
What will be the output?
__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:
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?