bhylu.com

Advertisements

__add__

__add__ can define meaningful addition for your type. Use it only when callers can predict what adding two objects means.

Understand the idea

Return a new result when the type models a value, and return NotImplemented for unsupported operands. __iadd__ and __radd__ have separate roles; defining __add__ does not provide every arithmetic behaviour. Validate units so a cents object is not accidentally added to a distance or an unrelated integer.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Cents:
    def __init__(self, amount):
        self.amount = amount
    def __add__(self, other):
        if not isinstance(other, Cents):
            return NotImplemented
        return Cents(self.amount + other.amount)

print((Cents(250) + Cents(450)).amount)

Read the result

The result is 700 in the same cents unit.

Try one change

Check that the two original objects retain their amounts after addition.