Jacob Steinebronn
Jacob Steinebronn

Reputation: 863

Simple timer class destroying itself for some reason

I'm trying to make a simple timer class in python. The idea is to just call start() and stop() and it handles the work a little easier. It works as intended from one start() to stop(), but when I call start() again it throws an exception.

import time

class Timer:
    def start(self):
        self.start = time.time()
    def stop(self):
        print("Elapsed time: ",time.time()-self.start)

timer = Timer()
timer.start()
[i for i in range(100000)] #run something that takes a bit of time
timer.stop()
timer.start()

This code produces the following output:

Elapsed time:  0.007978439331054688
Traceback (most recent call last):
  File "filepath/imagepca.py", line 13, in <module>
    timer.start()
TypeError: 'float' object is not callable
Press any key to continue . . .

As you can see, the first start() works correctly, as does the stop(), but when I call start() again the program crashes. Why is this happening?

Upvotes: 0

Views: 48

Answers (1)

sonus21
sonus21

Reputation: 5388

import time

class Timer:
    def start(self):
        self.start = time.time()
    def stop(self):
        print("Elapsed time: ",time.time()-self.start)

timer = Timer()
timer.start()
[i for i in range(100000)] #run something that takes a bit of time
timer.stop()
timer.start()

This problem is coming due to the fact that you have function and instance variable with the same name.

import time

class Timer:
    def start(self):
        self.start_time = time.time()
    def stop(self):
        print("Elapsed time: ",time.time()-self.start_time)

This will perfectly fine.

Upvotes: 1

Related Questions