Modules -> OOP -> Dunder methods -> Arithmetic methods

Arithmetic methods


Related code
class Dog:
    """Represents a dog.

    attributes: name: str, age: int, energy: int
    """

    def __init__(self, name, age, energy):
        self.name = name
        self.age = age
        self.energy = energy

    def __str__(self):
        return f'Name: {self.name}, Age: {self.age}'

    def __gt__(self, other):
        return self.age > other.age

    def add(self, other):
        new_dog = Dog(self.name + other.name, self.age + other.age, self.energy + other.energy)
        return new_dog

murki = Dog("Murki", 2, 50)
reksi = Dog("Reksi", 1, 50)

Instead of using add to create a dog which is as old and has as much energy as two dogs, it would be better if we could do dog1 + dog2. Let's try to apply + two murki and reksi:

>>> murki + reksi
TypeError("unsupported operand type(s) for +: 'Dog' and 'Dog'")

Python doesn't know how to add them, we have to tell Python how it should add two dogs, just like we told add method.

In order to be able to apply arithmetic operators to dogs we have to overload the following dunder methods:

  • __add__ (addition)
  • __sub__ (difference)
  • __mul__ (multiplication)
  • __div__ (division)
  • __pow__ (power)
class Dog:
    ...
    def __add__(self, other):
        return "__add__ method is activated"
...

Now whenever we apply + to two dogs, this method is activated:

>>> murki + reksi
__add__ method is activated

We proved that __add__ is activated when we apply + to two dogs.

Now let's give meaning to this operator when applied to dogs. We already have an idea of what does adding two dogs mean for us, creating a dog as old and with as much energy as the input dogs. This is the implementation of add method. So let's just rename this method:

class Dog:
    ...
    def __add__(self, other):
        new_dog = Dog(self.name + other.name, self.age + other.age, self.energy + other.energy)
        return new_dog
...
>>> sharki = murki + reksi
>>> print(sharki)
Name: MurkiReksi, Age: 3
>>> sharki.energy
100

Arithmetic operators don't make much sense in the case of dogs, but for testing purposes you can go on implementing other arithmetic dunder methods.