Modules -> OOP -> Case study: Time -> Adding times

Adding times


Related code
class Time:
    """Represents the time of day.
    attributes: hour, minute, second
    """

    def set(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second

    def print(self):
        print(f"{self.hour:02}:{self.minute:02}:{self.second:02}")

start = Time()
start.set(9, 45, 0)

duration = Time()
duration.set(1, 50, 0)

We're going to write a Time method, add, which takes two times and adds them:

class Time:
    ...
    def add(t1, t2):
        sum = Time()
        sum.hour = t1.hour + t2.hour
        sum.minute = t1.minute + t2.minute
        sum.second = t1.second + t2.second
        return sum
...

The method, add, creates a new Time object, initializes its attributes, and returns a reference to the new object. This is called a pure function because it does not modify any of the objects passed to it as arguments, and it has no effect, like displaying a value or getting user input, other than returning a value.

add, unlike other methods we have seen so far, takes two Time instances as arguments, t1 and t2. As we mentioned earlier, by convention, the first one is called self, the second one other (since the second argument is a Time instance too).

class Time:
    ...
    def add(self, other):
        sum = Time()
        sum.hour = self.hour + other.hour
        sum.minute = self.minute + other.minute
        sum.second = self.second + other.second
        return sum
...

To test this method, we already have two Time objects: start contains the start time of a movie, like Monty Python and the Holy Grail, and duration contains the run time of the movie, which is 1 hour 50 minutes. add figures out when the movie will be done.

>>> done = start.add(duration)
>>> done.print()
10:95:00

start is assigned to self, duration to other.

The result, 10:95:00 might not be what you were hoping for. The problem is that this method does not deal with cases where the number of seconds or minutes adds up to more than sixty. When that happens, we have to "carry" the extra seconds into the minute column or the extra minutes into the hour column.

Here is an improved version:

class Time:
    ...
    def add(self, other):
        sum = Time()
        sum.hour = self.hour + other.hour
        sum.minute = self.minute + other.minute
        sum.second = self.second + other.second

        if sum.second >= 60:
            sum.second -= 60
            sum.minute += 1
        if sum.minute >= 60:
            sum.minute -= 60
            sum.hour += 1

        return sum
...
>>> done = start.add(duration)
>>> done.print()
11:35:00