May-27-2020, 06:53 PM
Please consider the following Python code fragment:
f1 * f then it works. That is, the method __mul__ is called. However, if the user writes f * f1 then the function __mul__
is not called the program does not work. I would like to be able to define the fraction class such that f * f1 works. Is
that possible? and if so how?
Thanks,
Bob
import math
class Fraction:
def __init__(self,num,den):
if den < 0:
num = -num
den = -den
gcd = math.gcd( num, den )
self.num = num // gcd
self.den = den // gcd
def __str__(self):
return str(self.num) + '/' + str(self.den)
def __mul__(self, object):
if isinstance( object, float ) or isinstance( object, int ):
retValue = Fraction( object*self.num, self.den )
return retValue
if isinstance( object, Fraction ):
retValue = Fraction( self.num*object.num, self.den*object.den )
return retValue
return NoneAs written if the user has a variable of type float called f and an object of type Fraction called f1 and the user writesf1 * f then it works. That is, the method __mul__ is called. However, if the user writes f * f1 then the function __mul__
is not called the program does not work. I would like to be able to define the fraction class such that f * f1 works. Is
that possible? and if so how?
Thanks,
Bob
