本帖最后由 jackz007 于 2025-4-25 22:39 编辑
代码没有问题,只需要加上对象定义、方法调用、信息显示等代码即可看到效果
- # 以下是楼主的代码
- import time as t
- class MyTimer:
- def __str__(self):
- return self.prompt
- __repr__ = __str__
- #开始计时
- def start(self):
- self.begin = t.localtime()
- print('开始计时...')
- #停止计时
- def stop(self):
- 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])
- self.prompt += str(self.lasted[index])
- # 以下是新添加的代码
- r = MyTimer()
- r . start()
- t . sleep(10)
- r . stop()
- print(r . prompt)
复制代码
把上面的代码保存为文件 "mt.py"
【运行实况】:
- D:\[00.Exercise]\[Python]>python mt.py
- 开始计时...
- 停止计时
- 总共运行0000010
- D:\[00.Exercise]\[Python]>
复制代码