2012-10-29 45 views
1

我有這樣的事情:TypeError:start()只需要1個參數(0給定)?

class thread1(threading.Thread): 
    def __init__(self): 
     file = open("/home/antoni4040/file.txt", "r") 
     data = file.read() 
     num = 1 
     while True: 
      if str(num) in data: 
       clas = ExportToGIMP 
       clas.update() 
      num += 1  
thread = thread1 
     thread.start() 
     thread.join() 

我得到這個錯誤:

TypeError: start() takes exactly 1 argument (0 given) 

爲什麼?

回答

5

thread = thread1需要爲thread = thread1()。否則,你試圖調用類的方法,而不是類的實際實例。


另外,不要忽略__init__一個Thread對象做你的工作 - 覆蓋run

(雖然你可以覆蓋__init__做設置,實際上並不是在一個線程中運行,並且需要調用super()爲好。)


這裏怎麼你的代碼看起來應該'S:

class thread1(threading.Thread): 
    def run(self): 
     file = open("/home/antoni4040/file.txt", "r") 
     data = file.read() 
     num = 1 
     while True: 
      if str(num) in data: 
       clas = ExportToGIMP 
       clas.update() 
      num += 1  

thread = thread1() 
     thread.start() 
     thread.join() 
3

當你寫

thread = thread1 

要分配到thread類別thread1,即thread成爲thread1的同義詞。出於這個原因,如果你再寫入thread.start()你得到這個錯誤 - 你沒有通過self

調用一個實例方法,你真正想要的是什麼實例化thread1

thread = thread1() 

所以thread變爲實例thread1,您可以在其上調用實例方法,如start()

順便說一下,使用threading.Thread的正確方法是覆蓋run方法(在其中編寫要在另一個線程中運行的代碼),而不僅僅是構造函數。

相關問題