I have these two classes and they should remain separate classes, but I have a feeling that this could be implemented more efficiently and with less duplicate code. After googling around I still didn't figure a better way, so perhaps someone here could point me out. Ideally I want to get tick() method from Clock and just add alarm to it and also get set_time() method with additional attributes for setting the alarm time.
class Clock:
def __init__(self, hours, minutes, seconds):
self.set_time(hours, minutes, seconds)
def set_time(self, hours, minutes, seconds):
if hours < 0:
self.hours = 0
elif hours > 23:
self.hours = 23
else:
self.hours = hours
if minutes < 0:
self.minutes = 0
elif minutes > 59:
self.minutes = 59
else:
self.minutes = minutes
if seconds < 0:
self.seconds = 0
elif seconds > 59:
self.seconds = 59
else:
self.seconds = seconds
def tick(self):
while True:
print(str(self.hours).zfill(2), ":", str(self.minutes).zfill(2), ":", str(self.seconds).zfill(2), sep="")
self.seconds += 1
time.sleep(1)
if self.seconds == 60:
self.seconds = 0
self.minutes += 1
if self.minutes == 60:
self.minutes = 0
self.hours += 1
if self.hours == 24:
self.hours = 0
class AlarmClock(Clock):
def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec):
super().__init__(hours, minutes, seconds)
self.set_alarm(alarm_hr, alarm_min, alarm_sec)
def set_alarm(self, alarm_hr, alarm_min, alarm_sec):
if alarm_hr < 0:
self.alarm_hr = 0
elif alarm_hr > 23:
self.alarm_hr = 23
else:
self.alarm_hr = alarm_hr
if alarm_min < 0:
self.alarm_min = 0
elif alarm_min > 59:
self.alarm_min = 59
else:
self.alarm_min = alarm_min
if alarm_sec < 0:
self.alarm_sec = 0
elif alarm_sec > 59:
self.alarm_sec = 59
else:
self.alarm_sec = alarm_sec
def alarm(self):
while True:
print(str(self.hours).zfill(2), ":", str(self.minutes).zfill(2), ":", str(self.seconds).zfill(2), sep="")
self.seconds += 1
time.sleep(1)
if self.seconds == 60:
self.seconds = 0
self.minutes += 1
if self.minutes == 60:
self.minutes = 0
self.hours += 1
if self.hours == 24:
self.hours = 0
if self.hours == self.alarm_hr and self.minutes == self.alarm_min and self.seconds == self.alarm_sec:
print("ALARM ALARM ALARM ALARM ALARM!!!!")
break