Methods regarding Class Rational python

195 views Asked by At

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)
2

There are 2 answers

4
unutbu On

When Python evaluates X+Y, it first calls

X.__add__(Y)

if that returns NotImplemented, then Python calls

Y.__radd__(X)

This example demonstrates when __radd__ versus __add__ is called:

class Commuter:
    def __init__(self,val):
        self.val=val
    def __add__(self,other):
        print 'Commuter add', self.val, other
    def __radd__(self,other):
        print 'Commuter radd', self.val, other

x = Commuter(88)
y = Commuter(99)
x+1
# Commuter add 88 1

1+y
# Commuter radd 99 1

x+y
# Commuter add 88 <__main__.Commuter instance at 0xb7d2cfac>

In this case:

In [3]: (1).__add__(y)
Out[3]: NotImplemented

So y.__radd__(1) gets called.

0
Carl Groner On

Given the expression a + b, if object a implements __add__ it will be called with b:

a.__add__(b)

However, if a does not implement __add__ and b implements __radd__ (read as "right-add"), then b.__radd__ will be called with a:

b.__radd__(a)

The documentation explaining this is here.