Next / Previous / Contents / TCC Help System / NM Tech homepage


Describes an implementation of a class for representing rational numbers in the Python programming language.

This publication is available in Web form and also as a PDF document. Please forward any comments to

Table of Contents

1. Introduction
1.1. Related publications
2. The class interface
3. Contents of the module
3.1. Prologue
3.2. The gcd() function
3.3. class Rational
3.4. Rational.__init__(): The constructor
3.5. Rational.__add__(): Implement the addition (+) operator
3.6. Rational.__sub__(): Implement subtraction
3.7. Rational.__mul__(): Implement multiplication
3.8. Rational.__div__(): Implement division
3.9. Rational.__str__(): Convert a rational to a string
3.10. Rational.__float__(): Implement the float() function
3.11. Rational.mixed(): Display as a mixed fraction
3.12. rationaltest: A small test driver

1. Introduction

This document describes a Python module for working with rational numbers. It is intended as an example of a Python class for students new to object-oriented programming.

This publication assumes that the reader has had a general introduction to the construction of Python classes. In particular, you should know that the name of the class's constructor method is always __init__. Method names such as __init__, which start and end with two underbar (_) characters are called special methods.

This class makes heavy use of Python special methods to implement the common mathematical operators such as + and -. For example, when you have two instances x and y of some class, using the - (subtract) operator invokes the special method __sub__(x, y).

Relevant online files:

1.1. Related publications

Here are some links to related Python documentation: