Object-Oriented Programming · 18 min

Define how objects work with operators

Use special methods to give addition a clear meaning.

Jump to the automation lab

An expression like left + right lets Python ask left.__add__(right) for a result. Return a new value when addition should preserve both original objects.

Return NotImplemented for an unsupported operand. Python can then try the reflected operation and raise TypeError if neither operand supports the addition. NotImplementedError is a different object used to signal that code has not implemented a method.

Follow the example

Both objects store a count of minutes.

Run the example and practice

Add __add__ so two Duration objects produce a new Duration. Return NotImplemented for other operands. Print the sum with print(first + second) and then print first.

Target output

75 min
45 min
Show a hint

Use isinstance(other, Duration) before accessing other.minutes.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
class Duration:
    def __init__(self, minutes):
        self.minutes = minutes

    def __str__(self):
        return f"{self.minutes} min"

    def __add__(self, other):
        if not isinstance(other, Duration):
            return NotImplemented
        return Duration(self.minutes + other.minutes)

first = Duration(45)
second = Duration(30)
print(first + second)
print(first)

Automation lab

Combine two stock counts

Add two counts for the same item into a fresh object. Reject a mix of unrelated items.

Output

Ready

Run the example to see the output here.

Change the second item. Why should this operation raise an error?

Further reading in Automate the Boring Stuff with Python by Al Sweigart