Search code examples
pythonadditionmagic-methods

Must I override integer __add__ method to support addition of an integer and object?


So I am making a class called Complex which a representation of imaginary numbers (I know python has its own, but i want to make one myself). Thing is I want to construct an add method that supports addition of complex numbers as well as integers. So:

a = Complex(2, 4) + Complex(1, 1)
b = Complex(0, 3) + 3
c = 2 + Complex(4, 5)

should all be supported. As I understand,

object1 + object2

is the syntactic-sugar-equivalent of

object1.__add__(object2)

First and second examples are fine, but how do I get my class to support addition on the form INTEGER + COMPLEX? Do I have to override integer __add__method, if so; how do I do that, and is there another way?


Solution

  • you have to implement __radd__ on Complex.

    the way this works is pretty cool, if there's no existing implementation on an object for __add__, in your case, int + Complex, python will automatically check to see if __radd__ is implemented on the right-hand object.

    so it would be like:

    - does `int` have `__add__` for `Complex`? no
    - does `Complex` have `__radd__` for `int`? yes. cool, we've solved it
    

    the implementation would probably look something like:

    class Complex:
        def __radd__(self, other):
            return self + Complex(other)