← Python from Scratch Lesson 66 of 78 · 10 XP

Magic methods

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Methods with double underscores (__init__, __str__…) are called magic or dunder methods. Python calls them itself when you use ordinary syntax:

You write Python calls
str(v), print(v) v.__str__()
v in the interactive shell, inside a list v.__repr__()
a + b a.__add__(b)
a == b a.__eq__(b)
len(v) v.__len__()
a < b a.__lt__(b)

This way your objects start behaving like built-in types:

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __add__(self, other):
        return Money(self.amount + other.amount)

    def __eq__(self, other):
        return self.amount == other.amount

    def __str__(self):
        return f"{self.amount} ₸"

print(Money(100) + Money(50))    # 150 ₸

Without __eq__, two objects with the same data are not equal: by default == checks whether it's the same object.

Task. Create a class Vector with coordinates x and y. Adding vectors with + gives a new vector, == compares the coordinates, and str() gives (x, y).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.