Jack Frankland
Jack Frankland

Reputation: 11

Operator Overloading in Python coming from C++

I'm trying overload some operators in a Python class which represents a mathematical fraction. In particular I'm trying to overload the * operator so I can have fraction * fraction, fraction * integer and integer * fraction operations. I've had some experience with C++ and in that case I would write the operator overloads as in the Fraction class:

friend Fraction operator*(const Fraction &f1, const Fraction &f2);
friend Fraction operator*(const Fraction &f, int v);
friend Fraction operator*(int v, const Fraction &f);

My understanding is that C++ knows which function to resolve to based on the arguments you give it. However since in Python the function parameters aren't typed I'm confused as to how Python knows which operator overload to resolve to? For example:

def __mul__(self, other):
    return Fraction(self.numerator * other.numerator, self.denominator * other.denominator)

def __mul__(self,value):
    return Fraction(self.numerator * value,self.denominator)

The first overload will work for two fractions and the second for a fraction and an integer, but how does Python know which to use? I'm completely new to Python although I've been using C++ for a while.

Upvotes: 1

Views: 582

Answers (1)

deceze
deceze

Reputation: 522501

Python won't resolve functions by type at all. You can only have one method named __mul__ to begin with; not multiple versions of that method with different signatures. You will have to do type resolution by hand inside that one method if necessary:

def __mul__(self, other):
    if isinstance(other, int):
        ...

Note that it's pythonic to duck-type as much as possible, so you might want to check hasattr(other, 'numerator') instead of strict isinstance checks.

Upvotes: 3

Related Questions