python中建立一个时间类Time,它包含时hour、分minute、秒second的实例属性。(1)设计时间显示函数show(self)。(2)设计两个时间大小比较函数compare(self,t),其中t是另外一个时间
时间: 2024-12-26 22:30:35 浏览: 70
在Python中,我们可以创建一个名为`Time`的类来表示时间,包括小时(hour), 分钟(minute), 和秒(second)等属性。这里是一个简单的实现,包括`show()`函数来展示时间和`compare()`函数用于比较两个时间。
```python
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def show(self):
"""
显示时间
"""
print(f"{self.hour:02d}:{self.minute:02d}:{self.second:02d}")
def compare(self, t):
"""
比较两个时间,假设都是在同一分钟内
如果 t 的总秒数大于当前对象,则返回 True(t > self)
否则返回 False
"""
total_seconds_t = t.hour * 3600 + t.minute * 60 + t.second
total_seconds_self = self.hour * 3600 + self.minute * 60 + self.second
return total_seconds_t > total_seconds_self
# 示例
time1 = Time(9, 30, 0)
time2 = Time(10, 15, 0)
time1.show() # 输出: 09:30:00
if time1.compare(time2):
print("time1 比 time2 小")
else:
print("time1 比 time2 大")
阅读全文
相关推荐


















