+ 2
Christian Huml think of __radd__ as a backup function Python uses when __add__ is not found. here is a nice link https://blog.finxter.com/python-__rxadd__-magic-method/#:~:text=The%20Python%20__radd__()%20method,__add__(y)%20. and another good tutorial site https://python-course.eu/oop/magic-methods.php
30th Aug 2022, 11:49 AM
Bob_Li
Bob_Li - avatar
+ 2
r is for right. right add => radd Consider the expression a + b Usually the left operants (a in this case) __add__ function will be called. Like that: a.__add__(b) If - and only if - a does not implement __add__, than the right operant shall try performing that addition. To communicate to the object b that it's the right operant and not, as usual, the left one, the __radd__ function gets called instead, hence the name. That is necessary because not all additions work commutative. Therefore a+b might have another result than b+a. Consider the similar case a * b where a and b are matrices BUT of different classes. a does not implement __mul__ but b does implement __rmul__ If they were the same thing, a * b would now become b * a, which usually has another result (or even none at all for that matter) for matrices.
30th Aug 2022, 8:56 PM
Fynn Nix
Fynn Nix - avatar
+ 1
if you have __add__ and using it only on the same class, there is no need for __radd__ https://stackoverflow.com/questions/44394577/why-cant-i-replace-add-with-radd
30th Aug 2022, 3:02 PM
Bob_Li
Bob_Li - avatar