我有一个秒表,在后台使用线程进行排序,当它更新全局变量时,它不会更改我的class属性的输出
这就是我所拥有的:
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)”打印变量本身时,我得到了正确的秒数,因此class属性有问题,我不知道如何修复
您可以只使用一个类:
这就解决了问题
类变量在模块加载时初始化,因此
foo.time
在h、m和s为零时设置。但是,如果将其作为类方法,则会得到正确的结果:相关问题 更多 >
编程相关推荐