简体   繁体   中英

how to pass class self variable as a argument from Thread in python3?

i got error when run code:

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

output:

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'

and i can't send self as argument:

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

get error again:

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

You want to define your Thread on the __init__ of the class:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM