Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python operator overloading __radd__ and __add__

I'm currently learning python operator overloading (__radd__ and __add__ to be exact) and I have the following code

class Commuter1:
    def __init__(self, val):
        self.val = val
    def __add__(self, other):
        print('add', self.val, other)
        return self.val + other


    def __radd__(self, other):
        print('radd', self.val, other)
        return other + self.val


x = Commuter1(88)
y = Commuter1(99)

print(x + y)

I have got the following result

enter image description here

When used separately, I understand how __radd__ and __add__ works. But for the line x + y, I'm not sure why both __radd__ and __add__ methods are evoked.

like image 770
Thor Avatar asked Aug 31 '25 17:08

Thor


1 Answers

First, Python looks at the types of x and y to decide whether to call x.__add__ or y.__radd__. Since they're both the same type Commuter1, it tries x.__add__ first.


Then, inside your __add__ method, you do this:

return self.val + other

So, Python looks at the types of self.val and other to decide whether to call self.val.__add__ or other.__radd__. Since they're unrelated types int and Commuter1, it tries int.__add__ first.

But int.__add__ returns NotImplemented for a type it doesn't know about, so Python falls back to calling other.__radd__.


Inside your __radd__ method, you do this:

return other + self.val

So, Python looks at the types of other and self.val to decide whether to call other.__add__ or self.val.__radd__. Since they both the same type int, it tries __add__ first.


And of course int.__add__ works on another int, so it returns a value for the inner + inside your __radd__, which you return, which returns a value for the + inside __add__, which you return, which returns a value for the top-level +, which you print.

like image 61
abarnert Avatar answered Sep 02 '25 07:09

abarnert