← Back to challenges

Magic Methods in Classes

PythonHardclassesobjects

Instructions

Most people don't know about magic methods, which is sad, because they are incredibly powerful and are used in built-in functions such as int(), print(), repr(), and even iteration and indexing.

Use magic methods (don't forget __init__) to create a Number class.

Examples

__int__     # Used in the "int" method
__float__   # Used in the "float" method
__str__     # Used in the "str" method
__repr__    # Used in the "repr" method
__add__     # Used in the "+" operator function
__sub__     # Used in the "-" operator function
__mul__     # Used in the `*` operator function
__truediv__ # Used in the "/" operator function
__floordiv__# Used in the "//" operator function

Notes

N/A

python3
Loading editor…
to run
Walks through the solution with reasoning and edge cases.