python - Make an overloaded operator use an argument -
let's suppose have simple class defines rational number:
class rational(object): def __init__(self, numerator, denominator): self.n = numerator self.d = denominator def gcd(self): = self.n b = self.d while b: a, b = b, % b return def simplify(self): gcd = self.gcd() self.n = self.n / gcd self.d = self.d / gcd def __add__(self, other): rat = rational(self.n * other.d + self.d * other.n, self.d * other.d) rat.simplify() return rat now, whenever sum 2 rational instances, rational(2,3) + rational(1,3), method __add__ automatically simplifies number (returns rational(1,1)). like
def __add__(self, other, simp=true): rat = rational(self.n * other.d + self.d * other.n, self.d * other.d) if simp: rat.simplify() return rat and able rational(2,3) +(0) rational(1,3) returns rational(3,3) , of course rational(2,3) + rational(1,3) should yield rational(1,1).
Comments
Post a Comment