The program prints Expired the first time. I am expecting the code to print “not expired” for atleast 4 times before printing expired. Can someone please explain the reason and help me correct the code. Thank you
import time
TIMEOUT = 5
class Timer ():
def __init__(self):
self.timeout = time.time()+TIMEOUT
def isExpired ():
return time.time() > self.timeout
timing = Timer()
def main():
while 1:
if timing.isExpired:
print "Expired"
return
else:
print "Not expired"
print "sleeping for 1 second"
time.sleep(1)
if __name__== "__main__":
main()
You have several problems:
You did not give your
isExpiredmethod a self argument. Define it asdef isExpired(self):.You are creating a new Timer instance on each loop iteration. Move the
timing = Timer()outside the while loop.timing.isExpiredis a reference to the method object iself (which is always true in a boolean context). You need to dotiming.isExpired()to actually call it.These are all basic Python issues that have nothing to do with
Timer. Read the Python tutorial to learn how to use classes and so on.