This is an archived version of the course. Please see the latest version of the course.

Magic/Dunder methods

We have seen the special constructor method __init__() earlier.

Python offers more magic methods that can be used to make your custom classes act like Python built-in types.

Here are some examples:

  • __str__() is used when printing or converting an object into a string. In fact, str(x) invokes x.__str__(). For example, you might want print(person) to return something prettier and more informative than <__main__.Person object at 0x7ffe1cf127c0>.
  • __add__(), __sub__(), __mul__(), __truediv__(), __pow__() will overload their respective mathematical operators.
    • for example, x+y actually invokes x.__add__(y).
  • For overloading boolean operators: __lt__(), __le__(), __gt__(), __ge__(), __eq__(), __ne__() (<, <=, >, >=, ==, !=)
  • Collections:
    • __len__() (len(x) invokes x.__len__())
    • __contains__() (item in x invokes x.__contains__(item))
    • __getitem__() (x[key] invokes x.__getitem__(key))
    • __setitem__() (x[key] = item invokes x.__setitem__(key, item))
    • __iter__() is used to allow the type to be used in for loops

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Vector: 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y

    def __add__(self, other): 
        return Vector(self.x + other.x, self.y + other.y)

    def __str__(self): 
        return f"Vector ({self.x}, {self.y})"

v1 = Vector(1, 2) 
v2 = Vector(5, 7) 
v3 = v1 + v2
print(v3)