2017-09-01 70 views
0

我有一个类showAllThreads监视所有现有的线程在脚本(音乐播放器)变量Thread类没有显示正确的输出(蟒蛇)

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从mainthread访问musicQueue其中allThreads = showAllThreads()即使while循环执行musicQueue = True,它总是给我值False。我知道播放列表已打开,因为打印命令可以成功执行。

回答

1

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

我假定您是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)