python - 时钟类错误处理的最佳方法?

标签 python python-3.x class error-handling python-class

我希望代码停止工作并返回输入时间(小时)等无效,因为它不在1到24之间。但是,由于该类的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

关于python - 时钟类错误处理的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64392945/

相关文章:

python-3.x - 如何使用 Dash 在具有大型数据帧的数据表中提供分页

python - 如何设置平滑过渡的 Windows 10 桌面背景?

C++ 唯一类名与命名空间

Java类相互引用

c++ - 在构造函数 C++ 中将指针传递给 self

python - 从 Scrapy 中的管道和中间件关闭数据库连接

python - 读取保存在文本文件中的源页面并提取文本

python - Django 表单中的只读字段

python - 我一直在使用字典键作为成员标记。这是一个好主意吗?

html - 如何 : Active State During Server Action w/o JavaScript