You are here

Time

8 September, 2015 - 10:43

As another example of a user-defined type, we’ll define a class called Time that records the time of day. The class definition looks like this:

class Time(object):
"""Represents the time of day.
 
attributes: hour, minute, second
"""

We can create a new Time object and assign attributes for hours, minutes, and seconds:

time = Time()time.hour = 11time.minute = 59time.second = 30

The state diagram for the Time object looks like Figure 16.1.

Exercise 16.1.Write a function calledprint_timethat takes a Time object and prints it in the formhour:minute:second. Hint: the format sequence'%.2d'prints an integer using at least two digits, including a leading zero if necessary.

Exercise 16.2.Write a boolean function calledis_afterthat takes two Time objects,t1andt2, and returnsTrueift1followst2chronologically andFalseotherwise. Challenge: don’t use an if statement.