Home > Software engineering >  Python using class with loops working with time and datetime doesn't reset the timers
Python using class with loops working with time and datetime doesn't reset the timers

Time:10-04

I have tried to work with a while loop to keep my script running, I use time to track the time it takes to run. Simpler code it's something like this:

import time
import datetime

class Test:
    start = time.time()
    dateStart = datetime.datetime.now()

    def end(self):
        time.sleep(10)
        print(time.time() - self.start)
        print(datetime.datetime.now() - self.dateStart)

while True:
    test = Test()
    test.end()

and also tried with:

import time
import datetime

class Test:
    start = time.time()
    dateStart = datetime.datetime.now()

    def end(self):
        time.sleep(10)
        print(time.time() - self.start)
        print(datetime.datetime.now() - self.dateStart)

def runClass(classtest):
    test = classtest()
    test.end()

while True:
    runClass(Test)

But the timers are not set to 0 after each reset, they accumulate. The rest of the values I have in my big class do reset to the initial value they have after the class is created, but not dates. Is there something I'm missing about how python manage time and classes? I'm starting to use classes more, so maybe I'm missing something about how they are define in memory?

CodePudding user response:

What you are missing is how classes are defined and instances created.

Your code:

class Test:
    start = time.time()
    dateStart = datetime.datetime.now()

executes exactly once when class Test is defined.

What you meant to write was this:

class Test:
    def __init__(self)
        self.start = time.time()
        self.dateStart = datetime.datetime.now()
    ...

The __init__() method is executed every time test = Test() executes which is what you are after.

btw, I think that your line: test = classtest() should be test = Test()

  • Related