线程类中的变量未显示正确的输出(Python)

2024-09-27 23:22:25 发布

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

我有一个类showAllThreads,它监视脚本中所有现有的线程(音乐播放器)

class showAllThreads(threading.Thread):

    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        self.daemon = True
        self.start()

    #Shows whether the playing music is in queue, initially false
    musicQueue = False

    def run(self):
        while True:
            allThreads = threading.enumerate()
            for i in allThreads:
                if i.name == "PlayMusic" and i.queue == True:
                    musicQueue = True
                    print("Playlist is on")
                elif i.name == "PlayMusic" and i.queue == False:
                    musicQueue = False
                    print("Playlist is off")
                else:
                    musicQueue = False
            time.sleep(2)

当我试图通过allThreads.musicQueue其中allThreads = showAllThreads()从主线程访问musicQueue时,它总是给我值False,即使while循环执行musicQueue = True。我知道播放列表已打开,因为打印命令已成功执行


Tags: inselffalsetruequeueinitisdef
1条回答
网友
1楼 · 发布于 2024-09-27 23:22:25

您可以在两个地方定义“musicQueue”:首先在类级别(使其成为类属性-在类的所有实例之间共享的属性),然后在run()方法中将其定义为局部变量。这是两个完全不同的名称,因此您不能期望通过对局部变量赋值来以任何方式更改类级别1

我假设您是Python新手,没有花时间学习它的对象模型是如何工作的,以及它与大多数主流OOPL的区别。如果你希望喜欢用Python编写代码,你真的应该

显然,您希望在这里将musicQueue作为一个实例变量,并在run()内分配给它:

class ShowAllThreads(threading.Thread):

    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        self.daemon = True
        # create an instance variable
        self.musicQueue = False
        self.start()

    def run(self):
        while True:
            allThreads = threading.enumerate()
            for i in allThreads:
                if i.name == "PlayMusic" and i.queue == True:
                    # rebind the instance variable
                    self.musicQueue = True
                    print("Playlist is on")

                elif i.name == "PlayMusic" and i.queue == False:
                    self.musicQueue = False
                    print("Playlist is off")

                else:
                    self.musicQueue = False
            time.sleep(2)

相关问题 更多 >

    热门问题