Register to get access to free programming courses with interactive exercises

Level design Python: Building data abstractions

We will look at another simple system — rational numbers and the operations on them. Remember that we can represent a rational number as a fraction a/b, where a is the numerator and b is the denominator. Also, b cannot be zero since division by zero is not allowed.

Python does not support rational numbers. So, we will create an abstraction for them ourselves. As usual, we need a constructor and selectors:

# We have created a rational number
num = make_rational(1, 2)
numer = get_numer(num)
# 1
denom = get_denom(num)
# 2

We have defined a rational number using three functions. One function as a constructor assembles it from separate parts, and others as selectors allow us to extract them. In this case, it is unimportant what num is from a language point of view. You can do this with functions, lists, and dictionaries.

In the internal implementation, you can even use strings:

def make_rational(numer, denom):
    return f"{numer}/{denom}"

def get_numer(rational):
    numer, _ = rational.split('/')
    return numer

def get_denom(rational):
    _, denom = rational.split('/')
    return denom

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.