I've written a Time class that records the time of day and performs simple timing operations (add 2 times, convert a time object to an integer and back again,etc.) following the prompts in How to Think Like a Computer Scientist: Learning with Python.
class Time(object):
"""Attributes: hours, minutes, seconds"""
def __init__(self,hours,minutes,seconds):
self.hours =hours
self.minutes=minutes
self.seconds=seconds
def print_time(self):
"""prints time object as a string"""
print "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds)
def _str_(self):
"""returns time object as a string"""
return "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds)
def name(self,name):
"""names an instance"""
self.name=name
return self.name
def after(t1,t2):
"""checks to see which of two time objects is later"""
if t1.convert_to_seconds()<t2.convert_to_seconds():
return "%s is later" %(t2.name)
elif t1.convert_to_seconds>t2.convert_to_seconds:
return "%s is later" %(t1.name)
else:
return "these events occur simultaneously"
def convert_to_seconds(self):
"""converts Time object to an integer(# of seconds)"""
minutes=self.hours*60+self.minutes
seconds=minutes*60+self.seconds
return seconds
def make_time(self,seconds):
"""converts from an integer to a Time object"""
self.hours=seconds/3600
seconds=seconds-self.hours*3600
self.minutes=seconds/60
seconds=seconds-self.minutes*60
self.seconds=seconds
def increment_time(self, seconds):
"""Modifier adding a given # of seconds to a time object
which has been converted to an integer(seconds); permanently
alters object"""
sum=self.convert_to_seconds()+seconds
self.make_time(sum)
return self._str_()
def add_time(self, addedTime):
"""adds 2 Time objects represented as seconds;
does not permanently modify either object"""
import copy
end_time=copy.deepcopy(self)
seconds=self.convert_to_seconds()+addedTime.convert_to_seconds()
end_time.make_time(seconds)
return end_time._str_()
Usage examples:
breakfast=Time(8,30,7)
dinner=Time(19,0,0)
smokebreak=Time(19,0,0)
interval=(4,30,0)
print dinner.after(smokebreak)
print breakfast.add_time(interval)
print breakfast.increment_time(3600)
The Time Class example in the text I'm following does not use an init method, but passes straight into creating a time object and assigning attributes. Is there any advantage to including an init function, as I have done? Removing the init method seems to make it easier to adopt a terser and more functional style. Is including a method to name instances bad form, as I suspect? Would it be better write a functional-style version of add_time without importing deepcopy? I would appreciate any advice on best practices in Python 2.x OOP.