Next / Previous / Contents / Shipman's homepage

3.5. Rational.__add__(): Implement the addition (+) operator

This method will be invoked to perform the “+” operator whenever a Rational instance appears on the left side of that operator. To simplify life, we assume here that the operand on the right side is also a Rational instance.

Basically, what we are doing is adding two fractions. Here is the algebraic rule for adding fractions:

In this method, self is the left-hand operand and other is the right-hand operand.

rational.py
    def __add__ ( self, other ):
        """Add two rational numbers.
        """
        return Rational ( self.n * other.d + other.n * self.d,
                          self.d * other.d )