📚 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"""26minutes = hour * 60 + minute27self.seconds = minutes * 60 + second2829def __str__(self):30"""Returns a string representation of the time."""31minutes, second = divmod(self.seconds, 60)32hour, minute = divmod(minutes, 60)33return '%.2d:%.2d:%.2d' % (hour, minute, second)3435def print_time(self):36"""Prints a string representation of the time."""37print(str(self))3839def time_to_int(self):40"""Computes the number of seconds since midnight."""41return self.seconds4243def is_after(self, other):44"""Returns True if t1 is after t2; false otherwise."""45return self.seconds > other.seconds4647def __add__(self, other):48"""Adds two Time objects or a Time object and a number.4950other: Time object or number of seconds51"""52if isinstance(other, Time):53return self.add_time(other)54else:55return self.increment(other)5657def __radd__(self, other):58"""Adds two Time objects or a Time object and a number."""59return self.__add__(other)6061def add_time(self, other):62"""Adds two time objects."""63assert self.is_valid() and other.is_valid()64seconds = self.seconds + other.seconds65return int_to_time(seconds)6667def increment(self, seconds):68"""Returns a new Time that is the sum of this time and seconds."""69seconds += self.seconds70return int_to_time(seconds)7172def is_valid(self):73"""Checks whether a Time object satisfies the invariants."""74return self.seconds >= 0 and self.seconds < 24*60*60757677def int_to_time(seconds):78"""Makes a new Time object.7980seconds: int seconds since midnight.81"""82return Time(0, 0, seconds)838485def main():86start = Time(9, 45, 00)87start.print_time()8889end = start.increment(1337)90end.print_time()9192print('Is end after start?')93print(end.is_after(start))9495print('Using __str__')96print(start, end)9798start = Time(9, 45)99duration = Time(1, 35)100print(start + duration)101print(start + 1337)102print(1337 + start)103104print('Example of polymorphism')105t1 = Time(7, 43)106t2 = Time(7, 41)107t3 = Time(7, 37)108total = sum([t1, t2, t3])109print(total)110111112if __name__ == '__main__':113main()114115116