|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
各位大神,小弟刚刚学习python不久,跟随小甲鱼老师的视频一直学到魔法方法,现在有个问题没想明白,望各位大神救助.
就是定制计时器那一课的课后作业.
用到time模块中的perf_counter()方法. 我发现个问题在类中localtime()的方法直接调用就可以 ,为何per_counter()方法就会报AttributeError的错误.
截图和代码如下:
- import time as t
- class MyTimer:
- def __init__(self):
- self.test = "未开始计时"
- self.starttime = 0
- self.stoptime = 0
- self.calctime = 0
-
- def __str__(self):
- return self.test
-
- __repr__ = __str__
-
- # 修改add方法
- def __add__(self, other):
- calctime = float(self.test[5:-2]) + float(other.test[5:-2])
- test = "总共运行了 %.2f 秒" % calctime
- return test
-
- # 开始计时
- def start(self):
- self.starttime = t.perf_counter()
- self.test = "提示:请先调用stop()停止计时!"
- print("计时开始...")
-
- # 结束及时
- def stop(self):
- if not self.starttime:
- print("提示:请先调用start()开始计时!")
- else:
- self.stoptime = t.perf_counter()
- self._calc()
- print("计时结束!")
-
- # 内部计算时间
- def _calc(self):
- self.calctime = self.stoptime - self.starttime
- self.test = "总共运行了 %.2f 秒" % self.calctime
- print(self.test)
- # 为下一轮计算初始化变量
- self.starttime = 0
- self.stoptime = 0
- self.calctime = 0
复制代码 |
-
-
|