2013-08-22 47 views
0

我有一個類線程是這樣的:多線程參數路過

import threading, time 
class th(threading.Thread): 
    def run(self): 
     print "Hi" 
     time.sleep(5) 
     print "Bye" 

現在讓我們說,我想「沉睡」不同的每一次,所以我嘗試:

import treading, time 
class th(threading.Thread, n): 
    def run(self): 
     print "Hi" 
     time.sleep(n) 
     print "Bye" 

它不工作,它給我留言:

組參數必須是無,現在

那麼,如何在運行中傳遞參數?

注:我在班上像另一個函數做的:

import treading, time 
class th(threading.Thread): 
    def run(self): 
     print "Hi" 
     time.sleep(self.n) 
     print "Bye" 
    def get_param(self, n): 
     self.n = n 

var = th() 
var.get_param(10) 
var.start() 

回答

3

試試這個 - 你想要的超時值添加到對象,所以你需要的對象有一個變量作爲零件的。您可以通過添加創建類時執行的__init__函數來實現此目的。

import threading, time 
class th(threading.Thread): 
    def __init__(self, n): 
     self.n = n 
    def run(self): 
     print "Hi" 
     time.sleep(self.n) 
     print "Bye" 

查看更多詳情here

+0

'selfn'應該是'self.n'。 – user2357112

+0

謝謝。我沒有考慮它,這非常有幫助。 –

1
class Th(threading.Thread): 
    def __init__(self, n): 
     super(Th, self).__init__() 
     self.n = n 
    def run(self): 
     print 'Hi' 
     time.sleep(self.n) 

Th(4).run() 

定義一個構造函數,並將參數傳遞給構造函數。 class行的括號​​分隔父類的列表; n是一個參數,而不是父級。