1

我希望代码停止工作并返回输入时间(小时)等无效,因为它不在 1-24 之间。然而,由于类的 str 语句,无效时间仍然打印出来。无论如何在不打印无效时间的情况下显示错误。 我尝试使用 try/except 和 assert 来给出错误。

class clock():  
 def __init__(self,hour, minute, second):
   self.hour=hour
   self.minute=minute
   self.second=second
 def __str__(self):
  return str (self.hour)+":" + str(self.minute)+":"+str(self.second)
4

2 回答 2

0

接受的答案很好,但可以通过更好的错误消息进行一些改进:

class Clock:
    def __init__(self, hour, minute, second):
        if hour not in range(24):
            raise ValueError('hour not in range(24)')
        if minute not in range(60):
            raise ValueError('minute not in range(60)')
        if second not in range(60):
            raise ValueError('second not in range(60)')
        self.__hour = hour
        self.__minute = minute
        self.__second = second

    def __str__(self):
        return f'{self.__hour}:{self.__minute}:{self.__second}'

每当Clock类被错误地使用时,ValueError都会准确地说明出了什么问题。

于 2020-10-16T17:12:08.737 回答
0

永远不要允许无效状态存在。

class Clock():  
   def __init__(self, hour, minute, second):
       if not (0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60):
           raise ValueError("Clock values out of bounds")
       self.hour = hour
       self.minute = minute
       self.second = second
于 2020-10-16T16:25:44.890 回答