# 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
``````

• 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

Suggested learning programs
profession
new
Developing web applications with Django
10 months
from scratch
under development
Start at any time