This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Special methods

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

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

Here are some examples:

  • __str__() is used when printing. In fact, str() invokes x.__str__(). Useful if you want for example 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

class Vector: 
    def __init__(self, a, b): 
        self.a = a 
        self.b = b

    def __add__(self, other): 
        return Vector(self.a + other.a, self.b + other.b)

    def __str__(self): 
        return f"Vector ({self.a}, {self.b})"

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