我在使用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
对于第一个呼叫它按预期工作但是对于第二个呼叫,它给出了一个错误。我无法弄清楚错误的原因。
答案 0 :(得分:3)
当您编写self.start = time.time()
时,将函数start()
替换为名为start
的变量,该变量具有浮点值。下次你写timer.start()
时,start是一个浮点数,你试图把它称为函数。只需将名称self.start
替换为其他名称。
答案 1 :(得分:1)
我认为问题在于您对方法和属性使用相同的名称。
我会像这样重构它:
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'
答案 2 :(得分:0)
我认为现在我理解了您的问题和错误,以下更正您的问题:
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'
我希望有所帮助!