Next / Previous / Contents / Shipman's homepage

3.4. Rational.__init__(): The constructor

The constructor takes two external arguments, the numerator and the denominator. It finds the GCD of those two numbers and divides both of them by that GCD, to reduce the fraction to its lowest terms. It then stores the reduced numerator and denominator in the instance namespace under the attribute names n and d.
    def __init__ ( self, a, b ):
        """Constructor for Rational.
        if  b == 0:
            raise ZeroDivisionError, ( "Denominator of a rational "
                "may not be zero." )
            g  =  gcd ( a, b )
            self.n  =  a / g
            self.d  =  b / g