I previously asked the same question of why 10 .__add__(5.5) and 10. __radd__ (5.5) return NotImplemented but the question was closed due to possible duplicates.
The answer of one of the "duplicates" state that:
a + bdoes not directly translate toa.__add__(b). It also triesb.__radd__(a)ifa.__add__doesn't exist or returnsNotImplemented.
That answer suggests that either __add__ or __radd__ should work, but neither __add__ nor __radd__ really work as demonstrated in my code above.
The answer of the other "duplicate" state that:
a+b is equivalent to import operator; operator.add(a,b). It starts by calling
a.__add__(b)and then, if necessary,b.__radd__(a)
Again, neither __add__ nor __radd__ do the job. So, those answers are basically paraphrasing the Python docs on special methods which state that when a + operator occurs __add__ is called first and then __radd__ if __add__ was not successful. What happens when __radd__ is not successful either?
I think you didn't realize that the operators are swapped for the reverse operation. It's
b.__radd__(a)- it calls__radd__on the other operator!So because
10 .__add__(5.5)returnsNotImplementedit calls5.5 .__radd__(10)(which returns15.5) not10. __radd__ (5.5). If the__radd__on the swapped operators also returnsNotImplementedthe Python would raise an appropriateTypeError.This snippet demonstrates how the methods are called for
+(and what happens if both returnNotImplemented):Because
__radd__is only called if the class of the operands differ I needed to create a second class in this example.However you really shouldn't call special methods directly, if you need a function to perform such an operation you could use
operator.addin your case.