## 3. Contents of the `rational.py` module

The actual code of the `rational.py` module is displayed here, with commentary. This document is therefore an example of lightweight literate programming; see the author's page on The Cleanroom software development methodology for more information about the tools and techniques used in this document.

### 3.1. Prologue

The `rational.py` file starts with a module documentation string that describes the class interface. This is basically a restatement of the interface as described above, using Cleanroom intended functions to document each attribute and method. For more information, see The Cleanroom software development methodology.

rational.py
```'''rational.py:  Module to do rational arithmetic.

For full documentation, see http://www.nmt.edu/~shipman/soft/rational/.
```

To simplify fractions (for example, reducing 4/8 to 1/2), we will need a function to find the greatest common divisor of two numbers.

rational.py
```  Exports:
gcd ( a, b ):
[ a and b are integers ->
return the greatest common divisor of a and b ]
```

Here is the class constructor.

rational.py
```    Rational ( a, b ):
[ (a is a nonnegative integer) and
(b is a positive integer) ->
return a new Rational instance with
numerator a and denominator b ]
```

We make the numerator and denominator values available outside the class as visible attributes named `n` and `d`, respectively.

rational.py
```    .n:    [ the numerator ]
.d:    [ the denominator ]
```

We implement all four of the common mathematical operators: `+`, `-`, `*`, and `/`. These operations are implemented by defining methods that use certain special names, such as `__add__` for addition.

rational.py
```    .__add__(self, other):
[ other is a Rational instance ->
return the sum of self and other as a Rational instance ]
.__sub__(self, other):
[ other is a Rational instance ->
return the difference of self and other as a Rational
instance ]
.__mul__(self, other):
[ other is a Rational instance ->
return the product of self and other as a Rational
instance ]
.__div__(self, other):
[ other is a Rational instance ->
return the quotient of self and other as a Rational
instance ]
```

The built-in Python functions `str()` and `float()` are also implemented using special method names.

rational.py
```    .__str__(self):
[ return a string representation of self ]
.__float__(self):
[ return a float approximation of self ]
```

Finally, the `.mixed()` method that converts an instance to a string displaying the fraction as a mixed fraction:

rational.py
```    .mixed(self):
[ return a string representation of self as a mixed
fraction ]
'''
```