【问题标题】:How to create a class that returns military time如何创建一个返回军事时间的类
【发布时间】:2019-11-11 20:22:31
【问题描述】:

我创建了一个正确返回时间 hh:mm 格式的代码,但是当我在另一个文件中使用该代码时,与预期的输出相比,输出不正确。

例如:

它应该返回这个: 我们在 05:00 起床 我们 05:30 起床 06:10 我们又困了 末班车23:00发车 今天23:59结束 明天00:00开始

但我的回报: 我们在 05:00 起床 我们 05:30 起床 06:10 我们又困了 末班车23:00发车 今天23:59结束 明天24:00开始

第 24 小时应该变成 00:00,我不知道如何解决这个问题。

class MilClock:
    def __init__(self, hours, minutes):
        self.hours = int(hours)
        self.minutes = int(minutes)
    def __str__(self):
        return f"{self.hours:02}:{self.minutes:02}"
    def addOne(self):
        self.minutes += 1
        if self.minutes >= 60:
            self.minutes = 0
            self.hours += 1

''' 使用上面代码的下一个文件 '''

from milclock import *
def addMinutes(clock, n):
    for x in range(n):
        clock.addOne()
hallClock = MilClock(5,0)
print('We wake up at', hallClock)
addMinutes(hallClock, 30)
print('We get up at', hallClock)
addMinutes(hallClock, 40)
print('We are sleepy again by', hallClock)



wristWatch = MilClock(23,0)
print('Last tram leaves at', wristWatch)
addMinutes(wristWatch,59)
print('Today ends at', wristWatch)
wristWatch.addOne()
print('Tomorrow starts at', wristWatch)

【问题讨论】:

  • 也许你应该像 60 分钟一样换 24 小时?
  • 它只需要在您的 MilClock.addOne 方法中使用另一个 if 语句 - 就像您检查您的分钟数是否需要归零一样。

标签: python python-3.x function class time


【解决方案1】:

在您对addOne() 的定义中,尝试对小时数附加一个类似的测试,就像您已经对分钟数一样:

def addOne(self):
    self.minutes += 1
    if self.minutes >= 60:
        self.minutes = 0
        self.hours += 1
        if self.hours >= 24:
            self.hours = 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    相关资源
    最近更新 更多