如何在python3中从Thread传递类自变量作为参数?

时间:2015-12-22 20:46:12

标签: python multithreading python-3.x

运行代码时出错:

from threading import Thread
class c:
    var = False
    def wf(self):
            print(self.var)
    th = Thread(target=wf, args=())
    def test(self):
            self.th.start()
t = c()
t.test()

输出:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib64/python3.4/threading.py", line 920, in _bootstrap_inner
    self.run()
  File "/usr/lib64/python3.4/threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
TypeError: wf() missing 1 required positional argument: 'self'

我无法发送自己作为论点:

th = Thread(target=wf, args=(self))

再次出错:

Traceback (most recent call last):
  File "p.py", line 2, in <module>
    class c:
  File "p.py", line 8, in c
    th = Thread(target=wf, args=(self))
NameError: name 'self' is not defined

1 个答案:

答案 0 :(得分:3)

您想在班级的__init__上定义您的主题:

from threading import Thread


class c:
    th = None

    def __init__(self):
        self.th = Thread(target=self.wf, args=())

    var = False

    def wf(self):
        print(self.var)

    def test(self):
        self.th.start()


t = c()
t.test()
相关问题