TypeError after overriding the __add__ method

You need to define __radd__ as well to get this to work.

__radd__ is reverse add. When Python tries to evaluate x + y it first attempts to call x.__add__(y). If this fails then it falls back to y.__radd__(x).

This allows you to override addition by only touching one class. Consider for example how Python would have to evaluate 0 + x. A call to 0.__add__(x) is attempted but int knows nothing about your class. You can’t very well change the __add__ method in int, hence the need for __radd__. I suppose it is a form of dependency inversion.

As Steven pointed out, sum operates in place, but starts from 0. So the very first addition is the only one that would need to use __radd__. As a nice exercise you could check that this was the case!

Leave a Comment