我有一个类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
。我知道播放列表已打开,因为打印命令已成功执行
您可以在两个地方定义“musicQueue”:首先在类级别(使其成为类属性-在类的所有实例之间共享的属性),然后在
run()
方法中将其定义为局部变量。这是两个完全不同的名称,因此您不能期望通过对局部变量赋值来以任何方式更改类级别1我假设您是Python新手,没有花时间学习它的对象模型是如何工作的,以及它与大多数主流OOPL的区别。如果你希望喜欢用Python编写代码,你真的应该
显然,您希望在这里将
musicQueue
作为一个实例变量,并在run()
内分配给它:相关问题 更多 >
编程相关推荐