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

2024-04-30 04:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个秒表,在后台使用线程进行排序,当它更新全局变量时,它不会更改我的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属性有问题,我不知道如何修复


Tags: thetoname属性footimeglobalclass
2条回答

您可以只使用一个类:

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

这就解决了问题

类变量在模块加载时初始化,因此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())

相关问题 更多 >