Next / Previous / Contents / Shipman's homepage

3.9. Rational.__str__(): Convert a rational to a string

The __str__ method of a class is invoked whenever an instance of that class must be converted to a string. This happens, for instance, when you print an instance with a print statement, or when you use the str() function on an instance.

rational.py
    def __str__ ( self ):
        '''Display self as a string.
        '''
        return "%d/%d" % ( self.n, self.d )