How to think like a Computer Scientist: 课后习题第二十一章1-5

本文介绍了一个名为MyTime的Python类,该类用于表示时间,并提供了初始化、转化为秒、增加秒数、比较时间以及判断时间是否在另一时间段内的功能。通过实例展示了如何创建MyTime对象并进行操作。
摘要由CSDN通过智能技术生成
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      penglaixy
#
# Created:     19/09/2013
# Copyright:   (c) penglaixy 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------

class MyTime:
    def __init__(self, hrs =0, mins =0, secs=0):
        '''
        Create a MyTime object initialized to hrs,mins,secs
        '''
        total_secs = hrs*3600 + mins*60 + secs
        self.hours = total_secs//3600
        self.hours = self.hours%24
        left_secs = total_secs%3600
        self.mins = left_secs//60
        self.secs = left_secs%60

    def __str__(self):
        return "{0:02d}:{1:02d}:{2:02d}".format(self.hours, self.mins, self.secs)

    def to_seconds(self):
        '''
        Return th number of seconds represented by this instance
        '''
        return self.hours*3600 + self.mins*60 + self.secs

    def increment(self, secs):
        total_secs = self.to_seconds() + secs
        self.hours = total_secs//3600
        self.hours = self.hours%24
        left_secs = total_secs%3600
        self.mins = left_secs//60
        self.secs = left_secs%60

    def __gt__(self, other):
        '''
        Return True if time self is large than the time other,
        else False
        '''
        total_secs1 = self.to_seconds()
        total_secs2 = other.to_seconds()
        if total_secs1 > total_secs2:
            return True
        return False

    def between(self, other, test_time):
        '''
        test time test_time is between time self and time other
        if Yes, return True
        '''
        total_secs1 = self.to_seconds()
        total_secs2 = other.to_seconds()
        test_secs = test_time.to_seconds()

        if total_secs1 <= test_secs and test_secs < total_secs2:
            return True
        return False

def main():
    t1 = MyTime(25,12,30)
    print t1
    t2 = MyTime(2,67,90)
    print t2
    t3 = MyTime(24,69,89)
    print t3

    print t1.between(t2, t3)
    print t3.between(t2, t1)
    print t1 > t2
    print t1 > t3

    t1.increment(-60)
    print t1
    t1.increment(60)
    print t1
    t1.increment(3600*24)
    print t1


if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值