function - Operator Overloading in Python coming from C++ -
i'm trying overload operators in python class represents mathematical fraction. in particular i'm trying overload * operator can have fraction * fraction, fraction * integer , integer * fraction operations. i've had experience c++ , in case write operator overloads in 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 c++ knows function resolve based on arguments give it. since in python function parameters aren't typed i'm confused how python knows operator overload resolve to? 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 work 2 fractions , second fraction , integer, how python know use? i'm new python although i've been using c++ while.
python won't resolve functions type @ all. can have one method named __mul__
begin with; not multiple versions of method different signatures. have type resolution hand inside 1 method if necessary:
def __mul__(self, other): if isinstance(other, int): ...
note it's pythonic duck-type as possible, might want check hasattr(other, 'numerator')
instead of strict isinstance
checks.
Comments
Post a Comment