Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Research the __radd__ method. Explain in a paragraph how it differs from __add__

ID: 3593474 • Letter: R

Question

Research the __radd__ method. Explain in a paragraph how it differs from __add__.

When is it used? Implement __radd__ in the Fraction class

class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom

def __add__(self, otherFraction):
newNum = self.num * otherFraction.den +
self.den * otherFraction.num
newDen = self.den * otherFraction.den
common = self.gcd(newNum, newDen)
return Fraction(newNum // common, newDen // common)

def __eq__(self, other):
firstNum = self.num * other.den
secondNum = other.num * self.den
return firstNum == secondNum
  
def gcd(self, m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
  
def __str__(self):
return str(self.num) + "/" + str(self.den)

Explanation / Answer

Let us assume

x=Length(5,"ab")+3

x=3+Length(5,"ab")

The left side of the equation must be of type Length, because it apply the __add__ method which can't combine with Length object and second argument.

For this problem we can use __radd__ method. It evalutes the expression like this

3+Lenght(5,"ab")). Firstly it calls int.__add__(3,Length(3,"ab")), which will give an exception. After getting the expression it will try to invoke Length.__add__(Length(5,"ab"),3)

def__radd__(self,otherFraction):

Relation between __add__ and __radd__

self=5 and otherFraction=3

self=3 and otherFraction=5

-----------------------------------------------------------------------------

given add code

def __add__(self, otherFraction):
newNum = self.num * otherFraction.den +
self.den * otherFraction.num
newDen = self.den * otherFraction.den
common = self.gcd(newNum, newDen)
return Fraction(newNum // common, newDen // common)

replaced by __radd__

def __radd__(self, otherFraction):

res=self+otherFraction
newNum = self.num * otherFraction.den +
self.den * otherFraction.num
newDen = self.den * otherFraction.den
   return res

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote