A worked example: the Fraction class

22-minute lesson · module-classes-deeper-01

You are previewing this course as a guest

Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.

Sign in

A worked example: the Fraction class

22-minute lesson · module-classes-deeper-01

  • Build a Fraction class with a numerator and denominator.
  • Compute the greatest common divisor with Euclid's algorithm.
  • Reduce a fraction to lowest terms inside the constructor.
  • Define `__str__` to print a fraction as "n/d".

Source attribution

Status: adapted

How to Think Like a Computer Scientist: Interactive Edition source · Classes and Objects - Digging a Little Deeper / Fractions

Adaptation notes. Reading rewritten in our voice. The Fraction class is built step by step with a hand-written gcd (Euclid's algorithm) so students see the reduction logic rather than importing it. Hidden tests check reduction to lowest terms and the string form.

License notes. Original chapter is GNU FDL 1.3 (Brad Miller and David Ranum). No verbatim text from the original is reproduced here.