python建立一个时间关Time,它包含附 hour,分 minuts. 秒second的 实例居性 Q)资计时目显示方法sheox (se19: 茨诗万个时后大小比较的方劳coinaecalgo + 外一个时间
时间: 2024-03-21 07:37:56 浏览: 23
好的,针对您的问题,我可以给出如下的 Python 代码来实现:
```python
class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def show_time(self):
print("%02d:%02d:%02d" % (self.hour, self.minute, self.second))
def compare_time(self, other_time):
if self.hour > other_time.hour:
return 1
elif self.hour < other_time.hour:
return -1
else:
if self.minute > other_time.minute:
return 1
elif self.minute < other_time.minute:
return -1
else:
if self.second > other_time.second:
return 1
elif self.second < other_time.second:
return -1
else:
return 0
time1 = Time(9, 30, 0)
time2 = Time(13, 45, 30)
time1.show_time()
time2.show_time()
result = time1.compare_time(time2)
if result == 1:
print("time1 大于 time2")
elif result == -1:
print("time1 小于 time2")
else:
print("time1 等于 time2")
```
这段代码定义了一个名为 Time 的类,包含三个属性 hour、minute 和 second,以及两个方法 show_time 和 compare_time。show_time 方法用于显示当前时间,compare_time 方法用于比较当前时间与另一个时间的大小关系。
在主程序中,首先创建了两个 Time 对象 time1 和 time2,分别表示 9:30:00 和 13:45:30。然后调用 show_time 方法显示这两个时间。最后调用 compare_time 方法比较这两个时间的大小关系,并输出结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)