Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
from fractions import gcd


class Fraction:
    def __init__(self,numerator,denominator):
        assert denominator != 0, "nenner muß nicht null sein"
        if denominator < 0:
            (numerator,denominator) = (-numerator,-denominator)
        gcden = gcd(numerator,denominator)
        self.__num = numerator // gcden
        self.__den = denominator // gcden
    @property
    def numerator(self):
        return self.__num
    @property
    def denominator(self):
        return self.__den

    def __mult__(self,other):
        new_num = self.numerator * other.numerator
        new_den = self.denominator * other.denominator
        return Fraction(new_num,new_den)


f1 = Fraction(2,6)
f2 = Fraction(5,25)


f3 = f1 * f2 

if __name__ == '__main__':
    print(f1.numerator,f1.denominator)
    print(f2.numerator,f2.denominator)
    print('------')
    print(f3.numerator,f3.denominator)


it raisis the error
gcden = gcd(numerator,denominator)
Traceback (most recent call last):
  File "zwölf.py", line 127, in <module>
    f3 = f1 * f2 
TypeError: unsupported operand type(s) for *: 'Fraction' and 'Fraction'


What I have tried:

if __name__ == '__main__':
    print(f1.numerator,f1.denominator)
    print(f2.numerator,f2.denominator)
    print('------')
    print(f3.numerator,f3.denominator)
Posted
Updated 20-Aug-20 6:34am

1 solution

You cannot use the simple multiplication operator (*) for the fraction types as it is not defined anywhere in your class. You need to call __mult__ thus:
Python
f3 = f1.__mult__(f2)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900