i wrote the two methods, i still see no difference between the two methods..my class works fine so far , but since the methods are written the same, i still can't understand why when i do : x+1 it calls add , and 1+x it calls radd ?
def __add__(self,other):
assert isinstance(other,(Rational,int,str))
other=Rational(other)
n = self.n * other.d + self.d * other.n
d = self.d * other.d
return Rational(n, d)
def __radd__(self,other):
assert isinstance(other,(Rational,int,str))
other=Rational(other)
n =self.d * other.n + other.d * self.n
d=other.d * self.d
return Rational(n, d)
When Python evaluates
X+Y
, it first callsif that returns NotImplemented, then Python calls
This example demonstrates when
__radd__
versus__add__
is called:In this case:
So
y.__radd__(1)
gets called.