In general, writing two pieces of code that do the same thing is poor practice. If two operations, in this case add to another object when self is on the left and add to another object when self is on the right, ultimately perform the same operation it would be best practice to simply have __radd__
call __add__
and return the results of that. This way if you modify the behaviour of fraction addition, for example if you wanted to add the ability to use floats, you only need to modify code in one place instead of two.
Do note that you don't need to reverse the arguments; whether you use __radd__
or __add__
, self
is always the first argument. In the docs the example is given x - y
where x does not implement subtraction. The call made is y.__rsub__(x)
, so self will always be your object. So you still need to check the type of other, since self is the one that will always be a fraction.
(see: Documentation for __radd__
)
My implementation, assuming all else the same would be:
def __add__(self, other):
# however you want to implement __add__
def __radd__(self, other):
return self.__add__(other)
Edit:
Note that this only works if operand order doesn't matter. For subtraction, you would have to convert other to a fraction first, and then call __sub__
on that.
def __sub__(self, other):
# however you implement __sub__
def __rsub__(self, other):
if type(other) != Fraction:
if type(other) == int:
other = Fraction(other, 1)
else:
return NotImplemented
return other.__sub__(self)
Also, for safe use with all types, you may want have an else: return NotImplemented
or raise an error if the type is something other than float or int. Right now your class's behaviour with other object types is undefined. For example if I have an object with properties named num and den, but but mine are are a float and a string respectively, the error your code will give me is "you must pass integers as numerator and denominator", from the constructor, rather than something more intuitive like "Adding type Fraction with type MyType is not implemented".