gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:56:16 26 4
gpt4 key购买 nike

我希望代码停止工作并返回输入时间(小时)等无效,因为它不在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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com