魔法方法:简单定制 问题求助
在看小甲鱼的第44讲,制作一个计时器,代码如下:import time as t
class MyTimer():
#开始计时
def start(self):
self.start1 = t.localtime()
print('Timing starts')
#结束计时
def stop(self):
self.stop1 = t.localtime()
self.total()
print('Timing stops')
#计时计算
def total(self):
self.last = []
self.prompt = 'It\'s '
for each in range:
self.last.append(self.stop1-self.start1)
self.prompt += str(self.last)
print(self.prompt)
运行之后,报错:
>>> t = MyTimer()
>>> t.start()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
t.start()
File "F:\Programming\Python\practice\44.0.py", line 6, in start
self.start1 = t.localtime()
AttributeError: 'MyTimer' object has no attribute 'localtime'
求大佬解答!
对象名和里面的time模块的别名冲突了
t1 = MyTimer()
t1.start()
两个问题
首先变量名污染
你开头引用import time as t
后面 t = MyTimer()
t就失去了他的time属性
另外第十九行for each in range 改为for each in range(6)
附源码
import time as t
class MyTimer():
#开始计时
def start(self):
self.start1 = t.localtime()
print('Timing starts')
#结束计时
def stop(self):
self.stop1 = t.localtime()
self.total()
print('Timing stops')
#计时计算
def total(self):
self.last = []
self.prompt = 'It\'s '
for each in range(6):
self.last.append(self.stop1-self.start1)
self.prompt += str(self.last)
print(self.prompt)
>>> a=MyTimer()
>>> a.start()
Timing starts
>>> a.stop()
It's 000008
Timing stops
>>> t=MyTimer()
>>> t.start()
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
t.start()
File "C:\Users\admin\Desktop\f1.py", line 6, in start
self.start1 = t.localtime()
AttributeError: 'MyTimer' object has no attribute 'localtime'
页:
[1]