码迷,mamicode.com
首页 > 其他好文 > 详细

044魔法方法:简单定制

时间:2015-10-21 08:09:57      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:

基本要求:
--定制一个计时器的类
--start和stop方法代表启动计时和停止计时
--假设计时器对象t1,print(t1)和直接调用t1均显示结果
--当计时器未启动或已经停止计时,调用stop方法,会给予提示
--两个计时器对象可以进行相加:t1 + t2
--只能使用提供的有限资源完成

需要的资源:
    使用time模块的localtime方法获取时间
    time.localtime返回struct_time的时间格式
    表现你的类:__str__和__repr__


import time as t
 
class MyTimer:
    def __init__(self):
        self.unit = [‘年‘, ‘月‘, ‘天‘, ‘小时‘, ‘分钟‘, ‘秒‘]
        self.prompt = "未开始计时!"
        self.lasted = []
        self.begin = 0
        self.end = 0
     
    def __str__(self):
        return self.prompt
 
    __repr__ = __str__
 
    def __add__(self, other):
        prompt = "总共运行了"
        result = []
        for index in range(6):
            result.append(self.lasted[index] + other.lasted[index])
            if result[index]:
                prompt += (str(result[index]) + self.unit[index])
        return prompt
     
    # 开始计时
    def start(self):
        self.begin = t.localtime()
        self.prompt = "提示:请先调用 stop() 停止计时!"
        print("计时开始...")
 
    # 停止计时
    def stop(self):
        if not self.begin:
            print("提示:请先调用 start() 进行计时!")
        else:
            self.end = t.localtime()
            self._calc()
            print("计时结束!")
 
    # 内部方法,计算运行时间
    def _calc(self):
        self.lasted = []
        self.prompt = "总共运行了"
        for index in range(6):
            self.lasted.append(self.end[index] - self.begin[index])
            if self.lasted[index]:
                self.prompt += (str(self.lasted[index]) + self.unit[index])
        # 为下一轮计时初始化变量
        self.begin = 0
        self.end = 0

044魔法方法:简单定制

标签:

原文地址:http://www.cnblogs.com/wangjiaxing/p/4896671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!