I want to print dates in the following format:
23:59:59 Sunday
But all I get is this
23:59:59
This is my code:
class Counter:
def __init__(self, start=0):
self.value = start
def advance(self):
self.value = self.value + 1
def __str__(self):
return str(self.value)
class CyclicCounter(Counter):
def __init__(self, period, start=0):
self.period = period
Counter.__init__(self, start)
def advance(self):
self.value = (self.value + 1) % self.period
def __str__(self):
s = Counter.__str__(self)
return (len(str(self.period - 1)) - len(s)) * '0' + s
class CascadeCounter(CyclicCounter):
def __init__(self, next, period, start=0):
CyclicCounter.__init__(self, period, start)
self.next = next
def advance(self):
CyclicCounter.advance(self)
if self.next and self.value == 0:
self.next.advance()
class Clock(Counter):
def __init__(self, h, m, s):
super().__init__()
self._h = CyclicCounter(24, h)
self._m = CascadeCounter(self._h, 60, m)
self._s = CascadeCounter(self._m, 60, s)
def advance(self):
self._s.advance()
def __str__(self):
return '{0}:{1}:{2}'.format(self._h, self._m, self._s)
class DayCounter(CyclicCounter):
_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday']
day = ''
def __init__(self, day='Sunday'):
self.day = CyclicCounter.__init__(self, day)
def __str__(self):
return str(self.day)
class DayClock(Clock):
def __init__(self, h=0, m=0, s=0, day='Sunday'):
super().__init__(h, m, s)
self._d = DayCounter(day)
def __str__(self):
return Clock.__str__(self) + ' ' + str(self._d)
if __name__ == '__main__':
from time import sleep
clock = DayClock(23, 59, 45)
threshold = 5
while threshold > 0:
print(str(clock) + "\n")
sleep(1)
clock.advance()
threshold -= 1
As far as I can tell I do assign a value on the day attribute as well so I would expect it to be printed to but it doesnt. Specifically, in the main I create a DayClock, and I initialise the _d attribute with a DayCounter instance of the class that takes as input the string value of Sunday.
DayClock
doesn't have a __str__()
method that adds the day, it just inherits the method from Clock
. It should call the inherited method and then concatenate the day name to that.
class DayClock(Clock):
def __init__(self, h=0, m=0, s=0, day='Sunday'):
super().__init__(h, m, s)
self._d = DayCounter(day)
def __str__(self):
return Clock.__str__(self) + ' ' + str(self._d)
The DayCounter
class also seems to have some serious problems. Shouldn't it use _days.index(day)
to provide the start()
argument to CyclicCounter
? And the __str__()
method should return a string from _days
. I'm not going to try to fix all your bugs here, since the question was just about the DayClock
class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.