sv_jan5
sv_jan5

Reputation: 1573

Error while using python classes

I am facing some error while using classes in python 2.7

My class definition is:

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'

On executing the following code.

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

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

I am getting following error:

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

For the first call it worked as desired but for the second call, it gave an error. I am unable to figure out the cause of the error.

Upvotes: 0

Views: 109

Answers (3)

developer_hatch
developer_hatch

Reputation: 16224

I think now I understood your question and error, the following correct your issue:

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

If you rename the variable name, you have to remember to call first the start method so the start_value variable exists:

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')

but if you don't call the method and just do:

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

the variable start will never exist, wich throws to you the error:

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

I hope that helps!

Upvotes: 0

alec_djinn
alec_djinn

Reputation: 10789

I think the problem is that you are using the same name for a method and for an attribute.

I would refactor it like this:

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'

Upvotes: 1

blue note
blue note

Reputation: 29071

When you write self.start = time.time(), you replace the function start() with a variable named start, which has a float value. The next time you write timer.start(), start is a float, and you are trying to call it as a function. Just replace the name self.start with something else.

Upvotes: 3

Related Questions