3.4.1.12 The Timer class

dycanon · January 10, 2024
class Timer:
    def __init__(self, hh=0, mm=0, ss=0):
        self.__hours = hh
        self.__minutes = mm
        self.__seconds = ss

    def __str__(self):
        return ':'.join([timestr(self.__hours), \
                        timestr(self.__minutes), \
                        timestr(self.__seconds)])
    
    def next_second(self):
        
        if self.__seconds == 59:
            self.__seconds = 0
            self.__minutes += 1
        else:
            self.__seconds += 1
            
        if self.__minutes == 60:
            self.__minutes = 0
            self.__hours += 1

        if self.__hours == 24:
            self.__hours = 0


    def prev_second(self):
        
        if self.__seconds == 00:
            self.__seconds = 59
            self.__minutes -= 1
        else:
            self.__seconds -= 1

        if self.__minutes == -1:
            self.__minutes = 59
            self.__hours -= 1

        if self.__hours == -1:
            self.__hours = 23


def timestr(unit):
    unit = str(unit)
    if len(unit) == 1:
        unit = '0' + unit
        return unit
    return unit
    

timer = Timer(23, 59, 59)
print(timer)
timer.next_second()
print(timer)
timer.prev_second()
print(timer)
Output

Comments

Please sign up or log in to contribute to the discussion.