我正在尝试拒绝数据(转换为0),如果例如小时大于23,分钟大于60而第二大于60,但是我遇到了无法执行任何操作的问题。我不确定我是不是正确地初始化我的get / set方法或者是什么。
这是我的代码:
class Clock(object):
def __init__(self, hour, minute, second):
self.__hour = hour
self.__minute = minute
self.__second = second
def setHour(self, hour):
self.__hour = hour
if self.__hour > 23:
self.__hour = 0
def getHour(self):
return self.__hour
def setMinute(self, minute):
self.__minute = minute
if self.__minute > 60:
self.__minute = 0
def getMinute(self):
return self.__minute
def setSecond(self, second):
self.__second = second
if self.__second > 60:
self.__second = 0
def getSecond(self):
return self.__second
def __str__(self):
if self.__hour > 11:
return 'The Time is {}:{}:{} PM'.format(self.__hour, self.__minute, self.__second)
else:
return 'The Time is {}:{}:{} AM'.format(self.__hour, self.__minute, self.__second)
stopwatch = Clock(0, 0, 0)
print(stopwatch)
watch = Clock(10, 30, 0)
print(watch)
wallclock = Clock(5, 66, 42)
print(wallclock)
答案 0 :(得分:1)
您不会检查__init__
中的小时/分钟/秒是否超出界限。将您的__init__
更新为:
def __init__(self, hour, minute, second):
self.__hour = hour
if self.__hour > 23:
self.__hour = 0
self.__minute = minute
if self.__minute > 60:
self.__minute = 0
self.__second = second
if self.__second > 60:
self.__second = 0
或更好(跟随DRY - 不要重复自己):
def __init__(self, hour, minute, second):
self.setHour(hour)
self.setMinute(minute)
self.setSecond(second)
正如@brenbarn所提到的,您还可以调用底部的setHour,setMinute和setSecond方法来测试它们是否也有效:
stopwatch = Clock(0, 0, 0)
stopwatch.setHour(30)
print(stopwatch)
watch = Clock(10, 30, 0)
watch.setMinute(69)
print(watch)
wallclock = Clock(5, 66, 42)
wallclock.setSecond(70)
print(wallclock)
答案 1 :(得分:0)
是的,您无法在初始化函数中调用您的方法
我有另一种方法来实现您的想法,只需在您的班级中添加__setattr__
函数:
def __setattr__(self, name, value):
if name in ['__minute', '__second'] and value > 60:
return None
if name in ['__hour'] and value > 23:
return None
super().__setattr__(name, value)
此函数将检查值是否正确,如果值超出边界,则将值转换为0.这是一个pythonic函数。
答案 2 :(得分:0)
如果您使用的是Python 3,更好的解决方案是使用属性(简化为几小时),例如:
class Clock:
def __init__(self, hour, minute, second):
self._hour = self._minute = self._second = None
# Call the properties to apply validation rules
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return 'The Time is {:02}:{:02}:{:02}'.format(self._hour, self._minute, self.second)
@property
def hour(self):
return self._hour
@hour.setter
def hour(self, value):
self._hour = 0 if value > 23 else value
@property
def minute(self):
return self._minute
@minute.setter
def minute(self, value):
self._minute = 0 if value > 59 else value
@property
def second(self):
return self._second
@second.setter
def second(self, value):
self._second = 0 if value > 59 else value
PS你的代码允许61秒和分钟;)