运行代码时出错:
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
答案 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()