2017-09-01 51 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)