-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmagicmethod.py
More file actions
81 lines (58 loc) · 2.13 KB
/
magicmethod.py
File metadata and controls
81 lines (58 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# ---------- MAGIC METHODS ----------
# Magic methods are surrounded by double underscores
# We can use magic methods to define how operators
# like +, -, *, /, ==, >, <, etc. will work with our
# custom objects
# Magic methods are used for operator overloading
# in Python
# __eq__ : Equal
# __ne__ : Not Equal
# __lt__ : Less Than
# __gt__ : Greater Than
# __le__ : Less Than or Equal
# __ge__ : Greater Than or Equal
# __add__ : Addition
# __sub__ : Subtraction
# __mul__ : Multiplication
# __div__ : Division
# __mod__ : Modulus
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
# Magic method that defines the string format of the object
def __str__(self):
# :02d adds a leading zero to have a minimum of 2 digits
return "{}:{:02d}:{:02d}".format(self.hour,self.minute, self.second)
def __add__(self, other_time):
new_time = Time()
# ---------- PROBLEM ----------
# How would you go about adding 2 times together?
# Add the seconds and correct if sum is >= 60
if (self.second + other_time.second) >= 60:
self.minute += 1
new_time.second = (self.second + other_time.second) - 60
else:
new_time.second = self.second + other_time.second
# Add the minutes and correct if sum is >= 60
if (self.minute + other_time.minute) >= 60:
self.hour += 1
new_time.minute = (self.minute + other_time.minute) - 60
else:
new_time.minute = self.minute + other_time.minute
# Add the minutes and correct if sum is > 60
if (self.hour + other_time.hour) > 24:
new_time.hour = (self.hour + other_time.hour) - 24
else:
new_time.hour = self.hour + other_time.hour
return new_time
def main():
time1 = Time(1, 20, 30)
print(time1)
time2 = Time(24, 41, 30)
# After adding 24 hour in previous object.
print(time1 + time2)
# For homework get the Time objects to work for the other
# mathematical and comparison operators
main()