Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow a custom python class to add in both directions [duplicate]

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
like image 569
Mike Avatar asked Feb 03 '26 16:02

Mike


1 Answers

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.

like image 186
Mohammed Aouf Zouag Avatar answered Feb 05 '26 05:02

Mohammed Aouf Zouag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!