python建立一个时间类Time,它包含时hour,分minuie,秒second 的 实例属性 (1)设计时间显示方法 showr(selt): (2)设计两个时间大小比较的方法 compare(self,t),其中t是另外一个时间。
时间: 2024-03-23 10:37:09 浏览: 17
好的,下面是代码实现:
```python
class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def show_time(self):
time_str = '{:02d}:{:02d}:{:02d}'.format(self.hour, self.minute, self.second)
return time_str
def compare(self, t):
if self.hour > t.hour:
return 1
elif self.hour < t.hour:
return -1
else:
if self.minute > t.minute:
return 1
elif self.minute < t.minute:
return -1
else:
if self.second > t.second:
return 1
elif self.second < t.second:
return -1
else:
return 0
```
这里我们定义了一个 `Time` 类,它包含三个属性 `hour`、`minute` 和 `second`,分别表示时、分、秒。其中 `show_time` 方法可以将时间以字符串的形式返回,而 `compare` 方法可以比较两个时间的大小,返回值为 1、-1 或 0,分别表示第一个时间大于、小于或等于第二个时间。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.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)