写一个时间类time,表示某天的时间,包含属性:时,分,秒,通过运算符重载实现时间的加减法
时间: 2023-06-10 07:03:26 浏览: 83
好的,我可以为您编写一个时间类time。以下是示例代码:
```python
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return '{:02d}:{:02d}:{:02d}'.format(self.hour, self.minute, self.second)
def __add__(self, other):
total_seconds = self.hour * 3600 + self.minute * 60 + self.second \
+ other.hour * 3600 + other.minute * 60 + other.second
hour = total_seconds // 3600
minute = (total_seconds % 3600) // 60
second = total_seconds % 60
return Time(hour, minute, second)
def __sub__(self, other):
total_seconds = self.hour * 3600 + self.minute * 60 + self.second \
- (other.hour * 3600 + other.minute * 60 + other.second)
hour = total_seconds // 3600
minute = (total_seconds % 3600) // 60
second = total_seconds % 60
return Time(hour, minute, second)
```
这个time类具有时、分、秒三个属性,可以通过运算符重载实现时间的加减法操作。您可以使用加号(+)来将两个对象相加,使用减号(-)将它们相减,例如:
```python
>>> t1 = Time(10, 30, 0)
>>> t2 = Time(1, 15, 45)
>>> print(t1 + t2)
11:45:45
>>> print(t1 - t2)
09:14:15
```
请注意,该示例仅展示了一种实现方式,您可以设计您自己的时间类。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)
![](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)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)