Now we provide our example class with some attributes, that is, we give it defining data. In our case, this data will be the values of the denominator and the numerator. To this end, we have to define a method, __init__, used to initialize the class with these values:
class RationalNumber: def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator
Before we explain the special function __init__, which we added to the class, we demonstrate the instantiation of a RationalNumber object:
q = RationalNumber(10, 20) # Defines a new object q.numerator # returns 10 q.denominator # returns 20
A new object of type RationalNumber is created by using the class name as if it were a function. This statement does two things:
- It first creates an empty object, q.
- Then it applies the __init__ function to it; that is, q.__init__(10, 20) is executed.
The first parameter of __init__...