Search code examples
pythonclassoverridingaddition

Allow a custom python class to add in both directions


I have created a custom class that I want to be able to handle addition in both ways. As of now it only works if I have the class on the right hand side and the thing to add on the left (i.e. class+variable). How do I change the code below to include addition in the opposite direction (i.e. the other variable+class).

def __add__(self, other):
    return self.offset + other

Solution

  • Use the __radd__() special function:

    def __radd__(self, other):
        return self.offset + other
    

    This function will be called if the left operand does not support the addition operation and the operands are of different types.