python class attribute not updating when updated in a function

You could perhaps use just the one class:

import time
from threading import Thread


class stopwatch:
    def __init__(self):
        self.s = 0
        self.m = 0
        self.h = 0
        self.stopped = False
        self.name = "shirb"

    def begin(self):
        while self.stopped is False:
            self.s += 1
            if self.s >= 60:
                self.s = 0
                self.m += 1
            if self.m >= 60:
                self.m = 0
                self.h += 1
            time.sleep(1)

    def get_time(self):
        return str(self.h) + "h" + str(self.m) + "m" + str(self.s) + "s"


s = stopwatch()
Thread(target=s.begin).start()
input("press enter to stop the stopwatch")
s.stopped = True
print("Name: " + s.name + "\nTime: " + s.get_time())

This solves the issue.


Class variables are initialized at module load time, so foo.time is set when h, m, and s, are zero. If you make it a class method, however, you will get the right result:

class foo:
    name = 'shirb'
    
    @classmethod
    def cls_time(cls):
        return str(h) + 'h' + str(m) + 'm' + str(s) +'s'

Thread(target = stopwatch).start()
input('press enter to stop the stopwatch')
stopped = True
print('Name: ' + foo.name + '\nTime: ' + foo.cls_time())

Tags:

Python