多线程参数传递

2024-04-26 12:57:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个类线程:

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"

它不起作用,它给了我一个信息:

group argument must be None for now

那么,如何在运行中传递参数呢?你知道吗

注意:我是用类中的另一个函数完成的:

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()

Tags: runimportselftimevardefsleephi
2条回答
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是一个参数,而不是父类。你知道吗

试试这个-你想给对象添加超时值,所以你需要对象有这个变量作为它的一部分。可以通过添加在创建类时执行的__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。你知道吗

相关问题 更多 >