2013-08-22 43 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是一个参数,而不是父级。