python实例

我们将创建一个名为 Time 的类,该类可以表示时间(小时、分钟、秒),并支持时间的加减操作。我们将实现 __add__ 和 __sub__ 方法来支持时间的加减操作。

实例

class Time:
    def __init__(self, hours, minutes, seconds):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds
        self.normalize()
    def normalize(self):
        extra_minutes, self.seconds = divmod(self.seconds, 60)
        self.minutes += extra_minutes
        extra_hours, self.minutes = divmod(self.minutes, 60)
        self.hours += extra_hours
    def __add__(self, other):
        total_seconds = self.hours * 3600 + self.minutes * 60 + self.seconds
        total_seconds += other.hours * 3600 + other.minutes * 60 + other.seconds
        hours, remainder = divmod(total_seconds, 3600)
        minutes, seconds = divmod(remainder, 60)
        return Time(hours, minutes, seconds)
    def __sub__(self, other):
        total_seconds = self.hours * 3600 + self.minutes * 60 + self.seconds
        total_seconds -= other.hours * 3600 + other.minutes * 60 + other.seconds
        hours, remainder = divmod(total_seconds, 3600)
        minutes, seconds = divmod(remainder, 60)
        return Time(hours, minutes, seconds)
    def __str__(self):
        return f"{self.hours:02}:{self.minutes:02}:{self.seconds:02}"
# 示例使用
time1 = Time(2, 30, 45)
time2 = Time(1, 15, 20)
print("Time 1:", time1)
print("Time 2:", time2)
time_sum = time1 + time2
print("Time 1 + Time 2:", time_sum)
time_diff = time1 - time2
print("Time 1 - Time 2:", time_diff)

代码解析:

  1. __init__ 方法:初始化 Time 类的实例,接受小时、分钟和秒作为参数,并调用 normalize 方法确保时间的格式正确。

  2. normalize 方法:将秒和分钟转换为标准格式,确保秒数不超过 59,分钟数不超过 59。

  3. __add__ 方法:实现两个 Time 对象的加法操作,将时间转换为秒数相加,然后再转换回小时、分钟和秒。

  4. __sub__ 方法:实现两个 Time 对象的减法操作,将时间转换为秒数相减,然后再转换回小时、分钟和秒。

  5. __str__ 方法:返回格式化的时间字符串,确保小时、分钟和秒都是两位数。

输出结果:

Time 1: 02:30:45
Time 2: 01:15:20
Time 1 + Time 2: 03:46:05
Time 1 - Time 2: 01:15:25