Python Forum
Class and Operators in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class and Operators in Python
#1
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
Reply
#2
__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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Use of if - and operators Pedro_Castillo 1 487 Oct-24-2023, 08:33 AM
Last Post: deanhystad
  Mixing Boolean and comparison operators Mark17 3 1,405 Jul-11-2022, 02:20 AM
Last Post: perfringo
  Magic Method Arithmetic Operators ClownPrinceOfCrime 3 2,312 Jan-10-2021, 03:24 PM
Last Post: ndc85430
  Trying Comparison Operators PythonGainz 3 2,700 Mar-28-2020, 10:46 AM
Last Post: PythonGainz
  Mathematical Operators in String AgileAVS 1 2,378 Mar-04-2020, 04:14 PM
Last Post: Gribouillis
  A doubt with 'in' and 'not in' operators with strings newbieAuggie2019 7 3,583 Oct-23-2019, 03:11 PM
Last Post: perfringo
  understanding exponential and bitwise operators srm 1 2,043 Jun-15-2019, 11:14 AM
Last Post: ThomasL
  please help with this question about using operators to multiply a string? GilesTwigg 3 4,372 Feb-27-2019, 04:13 PM
Last Post: ichabod801
  Understanding compound operators -= NewatCode 3 3,169 Apr-25-2018, 05:03 PM
Last Post: Larz60+
  Pycharm shortcuts and operators don't run AzD 6 7,911 Oct-17-2017, 05:46 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020