Question

How Python chooses which object to use the method overload?

For example:

class a:
    def __init__(self, other):
        self.data = other
    def __add__(self, other):
        return self.data + other
    def __radd__(self,other):
        return self.data + other
X = a(1) 
X+1
1+X

Why in X + 1 expression , calls a method __add__ in object at the left, and in expression 1 + X method __add__ is called at object on the right?

Was it helpful?

Solution

X+1

first, calls:

X.__add__(1)

That succeeds, so no further work is needed.


On the other hand, this:

1+X

calls

(1).__add__(X)

That fails because int doesn't know how to interface with a class a. "As a last resort" this is tried instead:

X.__radd__(1)

From the docs on __radd__:

These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top