如何将self和2个参数传递给线程

2024-10-03 00:25:54 发布

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

我只是试图将self和另外两个参数传递给一个线程,但每次都会遇到一个错误。在

我试着跟踪其他样品,但到目前为止没有任何效果。在

class X:
    def start(self):
        newStartupThread = threading.Thread(target=self.launch, args=(t1_stop, 
            self.launchAdditionalParams))
        newStartupThread.name = "ClientLaunchThread%d" % 
            (self.launchAttemptCount+1)
        newStartupThread.daemon = True
        newStartupThread.start()


    def launch(self, test, additionalParams):
        pass

我得到了这个错误:

^{pr2}$

**编辑代码以显示它在类中


Tags: selftargetdef错误样品argslaunch线程
2条回答

根据self的存在,我假设这是在一个类中。在

import threading


class X:
    def start(self):
        t1_stop = 8
        self.launchAdditionalParams = {}

        newStartupThread = threading.Thread(
            target=self.launch,
            args=(t1_stop, self.launchAdditionalParams),
        )
        newStartupThread.name = "ClientLaunchThread"
        newStartupThread.daemon = True
        newStartupThread.start()

    def launch(self, test, additionalParams):
        print(locals())


x = X()
x.start()

对我来说很好,输出

^{pr2}$

launch是函数,不是方法。只有方法需要self参数。只要去掉自变量,它就会起作用:

def launch(test, additionalParams):

如果是在类中,则必须执行以下两种操作之一:

  • 在类的实例上调用它(someClass.launch(arg1, arg2)
  • 通过不包含self参数使其成为static method

相关问题 更多 >