编程练习:定义一个表示时间的类Time

定义一个表示时间的类Time ,它提供下面操作:
a)Time(hours,minutes,seconds)创建一个对象;
b) t.hours(),t.minutes(),t.seconds()分别 返回时间对象t的小时,分钟和秒值;
c)为Time对象定义加法和减法操作
d)定义时间对象的等于和小于关系运算

代码示例:

class Time:
    def __init__(self,hours,minutes,seconds):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds
    def hours(self):
        return self.hours

    def minutes(self):
        return self.minutes

    def seconds(self):
        return self.seconds

    def __add__(self,another):
        hours = ((self.hours*3600 + self.minutes*60 + self.seconds + another.hours*3600 + another.minutes*60 + another.seconds)//3600)
        minutes = ((self.hours*3600 + self.minutes*60 + self.seconds + another.hours*3600 + another.minutes*60 + another.seconds - 3600*hours)//60)
        seconds = (self.hours*3600 + self.minutes*60 + self.seconds + another.hours*3600 + another.minutes*60 + another.seconds - 60*minutes - 3600*hours)
        return Time(hours,minutes,seconds)

    def __sub__(self,another):
        hours = ((self.hours*3600 + self.minutes*60 + self.seconds - another.hours*3600 - another.minutes*60 - another.seconds)//3600)
        minutes = ((self.hours*3600 + self.minutes*60 + self.seconds - another.hours*3600 - another.minutes*60 - another.seconds - 3600*hours)//60)
        seconds = (self.hours*3600 + self.minutes*60 + self.seconds - another.hours*3600 - another.minutes*60 - another.seconds - 60*minutes - 3600*hours)
        return Time(hours,minutes,seconds)

    def __eq__(self,another):
        return self.hours*3600 + self.minutes*60 + self.seconds == another.hours*3600 + another.minutes*60 + another.seconds

    def __lt__(self,another):
        return self.hours*3600 + self.minutes*60 + self.seconds < another.hours*3600 + another.minutes*60 + another.seconds

    def print(self):
        print(self.hours,"h",self.minutes,"m",self.seconds,"s")

t1 = Time(1,20,33)
t2 = Time(2,25,47)
t3 = t2 - t1
t4 = t2 + t1
t3.print()
t4.print()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值