|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- <div>import time as t</div><div>class Time():
- def _init_(self):
- self.unit = ['年','月','日','时','分','秒']
- self.prompt='未开始计时'
- self.lasted=[]
- self.begin=0
- self.end=0
-
- def _str_(self):
- return self.prompt
-
- _repr_ = _str_</div><div> 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
- </div>
复制代码 结果:
=======================
>>> q=Time()
>>> q.start()
计时开始
>>> q.stop()
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
q.stop()
File "E:\python\程序\44_计时器.py", line 39, in stop
self._calc()
File "E:\python\程序\44_计时器.py", line 49, in _calc
self.prompt +=(str(self.lasted[index])+self.unit[index])
AttributeError: 'Time' object has no attribute 'unit'
>>>
在最开始不是有初始化self.unit = ['年','月','日','时','分','秒']吗?
为什么他还会报错说“Time”对象没有“unit”属性 ?
|
|