# Clock Class in Python Homework Sample

Create a class in Python that simulates a 24 hour clock, you can initialize the time with the hours, minutes and seconds, and call tick to advance the time by 1 second. The __str__ method should return the string as hh:mm:ss format with leading zeros. Write test cases to ensure the code behaves as expected. For more Python programming assignments contact us for details.

Solution:

clock.py

”’
Implentation of Class Clock which works with hr, min and sec and updates the clock
with method tick.

”’
class Clock:

def __init__(self, the_hr, the_min, the_sec):
self.hr = the_hr
self.min = the_min
self.sec = the_sec

def __str__(self):
return “{0:02d}:{1:02d}:{2:02d}”.format(self.hr, self.min, self.sec)

def tick(self):
self.sec += 1
if self.sec == 60:
self.sec = 0
self.min += 1

if self.min == 60:
self.min = 0
self.hr += 1

if self.hr == 24:
self.hr = 0

test.py

from clock import Clock
import unittest

class MyUnitTestClass(unittest.TestCase):

def test_1(self):
c1 = Clock(4, 7, 3)
self.assertEqual(str(c1), “04:07:03”)
self.assertEqual(c1.hr, 4)
self.assertEqual(c1.min, 7)
self.assertEqual(c1.sec, 3)
c1.tick( )
self.assertEqual(str(c1), “04:07:04”)

def test_2(self):
c2 = Clock(4, 7, 59)
self.assertEqual(str(c2), “04:07:59”)
c2.tick( )
self.assertEqual(str(c2), “04:08:00”)

def test_3(self):
c3 = Clock(4, 59, 59)
self.assertEqual(str(c3), “04:59:59”)
c3.tick( )
self.assertEqual(str(c3), “05:00:00”)

def test_4(self):
c4 = Clock(23, 59, 59)
self.assertEqual(str(c4), “23:59:59”)
c4.tick( )
self.assertEqual(str(c4), “00:00:00”)

if __name__ == ‘__main__’:
unittest.main( )