时钟错误处理的最佳方法 class?

Best possible method of error handling of clock class?

我希望代码停止工作并且 return 输入时间(小时)等无效,因为它不在 1-24 之间。然而,由于 class 的 str 语句,无效时间仍然打印出来。有没有显示错误而不打印出无效时间的方法。 我尝试使用 try/except 并断言给出错误。

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)

决不允许存在无效状态。

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

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

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 class 被错误使用时,ValueError 将准确说明错误所在。