Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96168
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
15
class Time:
16
"""Represents the time of day.
17
18
attributes: hour, minute, second
19
"""
20
def __init__(self, hour=0, minute=0, second=0):
21
"""Initializes a time object.
22
23
hour: int
24
minute: int
25
second: int or float
26
"""
27
minutes = hour * 60 + minute
28
self.seconds = minutes * 60 + second
29
30
def __str__(self):
31
"""Returns a string representation of the time."""
32
minutes, second = divmod(self.seconds, 60)
33
hour, minute = divmod(minutes, 60)
34
return '%.2d:%.2d:%.2d' % (hour, minute, second)
35
36
def print_time(self):
37
"""Prints a string representation of the time."""
38
print(str(self))
39
40
def time_to_int(self):
41
"""Computes the number of seconds since midnight."""
42
return self.seconds
43
44
def is_after(self, other):
45
"""Returns True if t1 is after t2; false otherwise."""
46
return self.seconds > other.seconds
47
48
def __add__(self, other):
49
"""Adds two Time objects or a Time object and a number.
50
51
other: Time object or number of seconds
52
"""
53
if isinstance(other, Time):
54
return self.add_time(other)
55
else:
56
return self.increment(other)
57
58
def __radd__(self, other):
59
"""Adds two Time objects or a Time object and a number."""
60
return self.__add__(other)
61
62
def add_time(self, other):
63
"""Adds two time objects."""
64
assert self.is_valid() and other.is_valid()
65
seconds = self.seconds + other.seconds
66
return int_to_time(seconds)
67
68
def increment(self, seconds):
69
"""Returns a new Time that is the sum of this time and seconds."""
70
seconds += self.seconds
71
return int_to_time(seconds)
72
73
def is_valid(self):
74
"""Checks whether a Time object satisfies the invariants."""
75
return self.seconds >= 0 and self.seconds < 24*60*60
76
77
78
def int_to_time(seconds):
79
"""Makes a new Time object.
80
81
seconds: int seconds since midnight.
82
"""
83
return Time(0, 0, seconds)
84
85
86
def main():
87
start = Time(9, 45, 00)
88
start.print_time()
89
90
end = start.increment(1337)
91
end.print_time()
92
93
print('Is end after start?')
94
print(end.is_after(start))
95
96
print('Using __str__')
97
print(start, end)
98
99
start = Time(9, 45)
100
duration = Time(1, 35)
101
print(start + duration)
102
print(start + 1337)
103
print(1337 + start)
104
105
print('Example of polymorphism')
106
t1 = Time(7, 43)
107
t2 = Time(7, 41)
108
t3 = Time(7, 37)
109
total = sum([t1, t2, t3])
110
print(total)
111
112
113
if __name__ == '__main__':
114
main()
115
116