Python Forum

Full Version: Class and Operators in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Please consider the following Python code fragment:

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 None
As written if the user has a variable of type float called f and an object of type Fraction called f1 and the user writes
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
__mul__ will implement f1 * f where f1 is instance of Fraction
you need to implement __rmul__ for f * f1
read https://docs.python.org/3/reference/data...t.__rmul__

and don't use object as argument, better use other as per convention or some other name