python入门——P44魔法方法:简单定制

写个计时器的类

import time as t
class Mytimer():

    def __init__(self):
        self.unit = ["year", "mouth", "day", "hour", "min", "sec"]
        self.begin = 0
        self.end = 0
        self.count = []
        self.prompt = "please start"

    def __str__(self):
        return self.prompt

    def __repr__(self):
        return print(self.prompt)

    def start(self): # 开始时间
        if not self.begin:
            self.begin = t.localtime()
            print("start")
        else:
            print("please stop")

    def stop(self): # 结束时间
        if not self.end:
            self.end = t.localtime()
            self._calc()
            print("stop")
        else:
            print("you are done")

    def __add__(self, other): #两个对象相加
        prompt = "All in all:"
        result = [] # 创建一个列表存相加后的结果
        for index in range(6):
            result.append(self.count[index] + other.count[index])
            if result[index]:
                prompt += str(result[index]) + self.unit[index]
        return prompt

    def _calc(self): # 计算相差时间
        self.count = [] # 定义一个空列表存差值
        self.prompt = "All in all:" # 最后需要打印出来的是字符串
        for index in range(6): # localtime是6位的,要循环进行减
            self.count.append(self.end[index] - self.begin[index])
            if self.count[index]:
                self.prompt += str((self.count[index])) + self.unit[index]

t1 = Mytimer()
t2 = Mytimer()
t1.start()
t1.start()
t.sleep(3)
t1.stop()
t1.stop()
print(t1)
t2.start()
t.sleep(4)
t2.stop()
print(t1 + t2)
start
please stop
stop
you are done
All in all:3sec
start
stop
All in all:7sec

这里还有个问题,连续两次运行stop会报错

你可能感兴趣的:(python入门,python)