无法弄清楚如何解决这个错误在Python类

问题描述:

我在Python初学者和揣摩什么是错的,如何解决这一短Python代码:无法弄清楚如何解决这个错误在Python类

from time import * 
class Stopwatch: 
    def __init__(self): 
     self.reset() 
    def start(self): 
     if not self.running: 
      self.start_time = clock() 
      self.running = True 
     else: 
      print('Stopwatch already running') 
    def stop(self): 
     if self.running: 
      self.elapsed += clock() - self.start_time 
      self.running = False 
     else: 
      print('stopwatch not running') 
    def reset(self): 
     self.start_time = self.elapsed = 0 
     self.running = False 
    def elapsed(self): 
     if not self.running: 
      return self.elapsed 
     else: 
      print("stopwatch must be stopped") 
      return None 

timer = Stopwatch() 
timer.start() 
sleep(2) 
print('I am awake \n') 
timer.stop() 
print(timer.elapsed()) 

--->我得到这个错误说TypeError:'浮动'对象不可调用 但为什么'浮动'不可调用? 感谢您的帮助 霍华德

你有一个在你的Stopwatch类命名为elapsed功能。没关系。然而,在stop方法设置self.elapsed是一个浮动:

self.elapsed += clock() - self.start_time 

当你调用timer.elapsed(),Python是不知道你指的是哪个elapsed。您已将self.elapsed重新分配为浮动。它抱怨并抛出一个错误,因为你不能调用一个float作为函数。

更改函数的名称,并且不抛出错误。例如,

def time_elapsed(self): 
    if not self.running: 
     return self.elapsed 
    else: 
     print("stopwatch must be stopped") 
     return None 

... 

print(timer.time_elapsed())