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