Home » Learn Python » Dunder (Magic) Methods » Adding Objects

Adding Objects

You can implement the __add__ dunder method to make it possible to add objects together.

Consider the addition operator, +. We can think of this as being like a function that accepts two arguments: the two things to be added together. It returns a new object of the same type as the objects being added.

When we implement __add__, it therefore accepts another object as an argument, and that should be “added” to the current object represented by self. A new object should be returned.

class Clock:
    def __init__(self, time):
        self._time = time

    def __str__(self):
        return f"It's {self._time} o'clock"
    
    # Don't let the time get bigger than 12 (hours)
    def __add__(self, other):
        newtime = (self._time + other._time) % 12
        return Clock(newtime)

c1 = Clock(8)
c2 = Clock(7) 

c3 = c1 + c2

print(c1)
print(c2)
print(c3)
It's 8 o'clock
It's 7 o'clock
It's 3 o'clock

Other Binary Operators

Other binary operators (accepting two arguments) can be implemented similarly, including __sub__ (subtract), __mul__ and many others.

Leave a Reply

Blog at WordPress.com.

%d