代码报错求帮助解决
本帖最后由 fc5igm 于 2021-6-16 15:47 编辑import time
class MyTimer:
def start(self):
self.start=time.time()
print('计时开始!')
def stop(self):
self.stop=time.time()
try:
self.lstm=round(float(self.stop)-(self.start))
print('计时结束!')
except (AttributeError,TypeError):
print('提示:请先调用start()开始计时!')
def __repr__(self):
try:
return f'总共运行了{self.lstm}秒'
except (AttributeError,TypeError):
return '未开始计时!'
def __str__(self):
try:
return f'总共运行了{self.lstm}秒'
except (AttributeError,TypeError):
return '未开始计时!'
def __add__(self,other):
print(int(self.lstm)+int(other.lstm))
t1=MyTimer()
>>> t1.start()
计时开始!
>>> t1.stop()
计时结束!
>>> t1
总共运行了4秒
>>> t1.start()
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
t1.start()
TypeError: 'float' object is not callable
>>> t1.start
1623825866.1460986
>>> t1.start()
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
t1.start()
TypeError: 'float' object is not callable
为什么t1.start()第一次调用就成功,第二次则报错了?另外,'float' object is not callable是什么意思?
我换成str字符串也报了一样的错误。那什么样子才是callable的? import time as t
class MyTimer():
def start(self):
self.start=t.localtime()
print('计时开始')
def stop(self):
self.stop=t.localtime()
print('计时结束')
self._calc()
def _calc(self):
self.lasted=[]
self.prompt='总共运行了'
for index in range(6):
self.lasted.append(self.stop-self.start)
self.prompt+=str(self.lasted)
print(self.prompt)
>>> t1=MyTimer()
>>> t1.start()
计时开始
>>> t1.stop()
计时结束
总共运行了00001-57
>>> t1.start()
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
t1.start()
TypeError: 'time.struct_time' object is not callable
>>> t1.start()
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
t1.start()
TypeError: 'time.struct_time' object is not callable
小甲鱼课上代码也出现了同样的问题。如果一个实例对象属性被赋值过一次,后边就不可以再被赋值第二次了么? 忘记属性和方法不能重名了
页:
[1]