📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division121314class Time:15"""Represents the time of day.1617attributes: hour, minute, second18"""19def __init__(self, hour=0, minute=0, second=0):20"""Initializes a time object.2122hour: int23minute: int24second: int or float25"""26self.hour = hour27self.minute = minute28self.second = second2930def __str__(self):31"""Returns a string representation of the time."""32return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)3334def print_time(self):35"""Prints a string representation of the time."""36print(str(self))3738def time_to_int(self):39"""Computes the number of seconds since midnight."""40minutes = self.hour * 60 + self.minute41seconds = minutes * 60 + self.second42return seconds4344def is_after(self, other):45"""Returns True if t1 is after t2; false otherwise."""46return self.time_to_int() > other.time_to_int()4748def __add__(self, other):49"""Adds two Time objects or a Time object and a number.5051other: Time object or number of seconds52"""53if isinstance(other, Time):54return self.add_time(other)55else:56return self.increment(other)5758def __radd__(self, other):59"""Adds two Time objects or a Time object and a number."""60return self.__add__(other)6162def add_time(self, other):63"""Adds two time objects."""64assert self.is_valid() and other.is_valid()65seconds = self.time_to_int() + other.time_to_int()66return int_to_time(seconds)6768def increment(self, seconds):69"""Returns a new Time that is the sum of this time and seconds."""70seconds += self.time_to_int()71return int_to_time(seconds)7273def is_valid(self):74"""Checks whether a Time object satisfies the invariants."""75if self.hour < 0 or self.minute < 0 or self.second < 0:76return False77if self.minute >= 60 or self.second >= 60:78return False79return True808182def int_to_time(seconds):83"""Makes a new Time object.8485seconds: int seconds since midnight.86"""87minutes, second = divmod(seconds, 60)88hour, minute = divmod(minutes, 60)89time = Time(hour, minute, second)90return time919293def main():94start = Time(9, 45, 00)95start.print_time()9697end = start.increment(1337)98#end = start.increment(1337, 460)99end.print_time()100101print('Is end after start?')102print(end.is_after(start))103104print('Using __str__')105print(start, end)106107start = Time(9, 45)108duration = Time(1, 35)109print(start + duration)110print(start + 1337)111print(1337 + start)112113print('Example of polymorphism')114t1 = Time(7, 43)115t2 = Time(7, 41)116t3 = Time(7, 37)117total = sum([t1, t2, t3])118print(total)119120121if __name__ == '__main__':122main()123124125