【问题标题】:Error while using python classes使用 python 类时出错
【发布时间】:2017-10-30 23:07:36
【问题描述】:

在 python 2.7 中使用类时遇到一些错误

我的班级定义是:

class Timer(object):

    def __init__(self):
        self.msg = ""

    def start(self,msg):
        self.msg = msg
        self.start = time.time()

    def stop(self):
        t = time.time() - self.start
        return self.msg, " => ", t, 'seconds'

在执行以下代码时。

timer = Timer()
timer.start("Function 1")
Some code
timer.stop()

timer.start('Function 2')
some code
timer.stop()

我收到以下错误:

Function 1 => 0.01 seconds
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable

对于第一次调用,它按预期工作,但对于第二次调用,它给出了错误。我无法找出错误的原因。

【问题讨论】:

  • t = time.time() - self.start 看起来不对。 self.start 是一个函数。
  • 是的,谢谢
  • self.start = time.time() 也是错误的
  • @sv_jan5 也是,这个问题非常有效,+1,我喜欢找到问题哈哈
  • @sv_jan5 确实!我实际上再次编辑了我的答案,所以它现在终于正确和完整了

标签: python python-2.7 class oop


【解决方案1】:

当您编写self.start = time.time() 时,您将函数start() 替换为一个名为start 的变量,该变量具有一个浮点值。下次你写timer.start() 时,start 是一个浮点数,你试图将它作为一个函数来调用。只需将名称 self.start 替换为其他名称即可。

【讨论】:

    【解决方案2】:

    我认为问题在于您对方法和属性使用相同的名称。

    我会这样重构它:

    class Timer(object):
    
        def __init__(self):
            self.msg = ""
            self.start_time = None #I prefer to declare it but you can avoid this
    
        def start(self,msg):
            self.msg = msg
            self.start_time = time.time()
    
        def stop(self):
            t = time.time() - self.start_time
            return self.msg, " => ", t, 'seconds'
    

    【讨论】:

      【解决方案3】:

      我想现在我理解了您的问题和错误,以下更正您的问题:

      import time
      
      class Timer(object):
      
        def __init__(self):
            self.msg = ""
      
        def start(self,msg):
            self.msg = msg
            self.start = time.time() # Here, your method name is the same has the variable name
      

      如果你重命名变量名,你必须记得先调用 start 方法,这样 start_value 变量才会存在:

      import time
      
      class Timer(object):
      
        def __init__(self):
            self.msg = ""
      
        def start(self,msg):
            self.msg = msg
            self.start_value = time.time() #Is you change the variable name, the problem is solved
      
        def stop(self):
            t = time.time() - self.start_value
            return self.msg, " => ", t, 'seconds'
      
      
      a = Timer()
      a.start("first call")
      print a.stop()
      
      >> ('first call', ' => ', 1.9073486328125e-06, 'seconds')
      

      但如果你不调用该方法而只是这样做:

      a = Timer()
      # a.start("first call") without it
      print a.stop()
      

      变量start 永远不会存在,它会向您抛出错误:

      AttributeError: 'Timer' object has no attribute 'start_value'
      

      希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 2015-08-03
        • 2018-09-28
        • 1970-01-01
        • 2018-07-25
        • 2018-07-28
        • 2014-10-14
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        相关资源
        最近更新 更多