python类属性在函数中更新时不更新

我有一个使用线程在后台运行的秒表,当它更新全局变量时,它不会更改我的类属性的输出。

这就是我所拥有的:

import time
from threading import Thread
s = 0
m = 0
h = 0
stopped = False

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

class foo:
    name = 'shirb'
    time = 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.time)

假设我等了 1 分 34 秒。输出应该是:

press enter to stop the stopwatch
Name: shirb
Time: 0h1m34s

但这就是它实际推出的内容:

press enter to stop the stopwatch
Name: shirb
Time: 0h0m0s

我不知道是什么导致它不更新。当我尝试用“print(s)”打印变量本身时,我得到了正确的秒数,所以类属性有问题,我不知道如何修复。

回答

类变量在模块加载时初始化,因此foo.time在 h、m 和 s 为零时设置。但是,如果将其设为类方法,则会得到正确的结果:

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


以上是python类属性在函数中更新时不更新的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>