Changes

Jump to: navigation, search

Rchan sandbox

2,561 bytes added, 09:10, 3 November 2019
Part 3 - Another approach to perform operation on time objects
:9. Before proceeding, make certain that you identify all errors in lab7a.py. When the checking script tells you everything is OK - proceed to the next step.
<br><br>
=Investigation II=
In the previous investigation, the functions that were defined for manipulating our time object are not tied directly to our time object. Given our time object alone, we won't be able to tell that there exist a function called sum_times() which can be used to add two time objects and return their sum.
To tie up those functions to our time objects, we only need to move those functions definition under the class block which define our Time object. The following illustration show how it should be done:
<source lang="python">
#!/usr/bin/env python3
# Student ID: rchan
class Time:
"""Simple object type for time of the day.
data attributes: hour, minute, second
function attributes: __init__, __str__, __repr__
time_to_sec, format_time,
change_time, sum_time
"""
def __init__(self,hour=12,minute=0,second=0):
"""constructor for time object"""
self.hour = hour
self.minute = minute
self.second = second
def format_time(self):
"""Return time object (t) as a formatted string"""
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
 
def sum_times(self, t2):
"""Add two time objests and return the sum."""
sum = Time(0,0,0)
sec1 = time_to_sec(self)
sec2 = time_to_sec(self)
sum = sec_to_time(sec1 + sec2)
return sum
 
def change_time(self, seconds):
time_seconds = time_to_sec(self)
nt = sec_to_time(time_seconds + seconds)
time.hour, time.minute, time.second = nt.hour, nt.minute, nt.second
return None
 
def time_to_sec(self):
'''convert a time object to a single integer representing the
number of seconds from mid-night'''
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds
 
def valid_time(t):
"""check for the validity of the time object attributes:
24 > hour > 0, 60 > minute > 0, 60 > second > 0 """
if t.hour < 0 or t.minute < 0 or t.second < 0:
return False
if t.minute >= 60 or t.second >= 60 or t.hour >= 24:
return False
return True
 
def sec_to_time(seconds):
'''convert a given number of seconds to a time object in
hour, minute, second format'''
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
</source>
:1. Create a new file and name it as '''lab7d.py''' and place the code above in it.
1,760
edits

Navigation menu