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

线程类中的变量未显示正确的输出(Python),python,multithreading,Python,Multithreading,我有一个类showAllThreads,它监视脚本中的所有现有线程(音乐播放器) 当我试图通过allThreads.musicQueue从主线程访问musicQueue时,其中allThreads=showAllThreads()总是给我值False,即使while循环执行musicQueue=True。我知道播放列表已打开,因为print命令已成功执行。您在两个位置定义“musicQueue”:首先在类级别(使其成为类属性-在类的所有实例之间共享的属性),然后在run()方法中作为局部变量。这

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

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

您在两个位置定义“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
        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)
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)