Lesson 03
Class Threads
Run a method of a Python class on a child thread by passing that method as the Thread target and supplying the method arguments as a tuple.
Run a method of a Python class on a child thread by passing that method as the Thread target and supplying the method arguments as a tuple.
Example
import threading
class Board:
def list_values(self, m):
print(threading.current_thread().name, list(range(1, m + 1)))
board = Board()
worker = threading.Thread(target=board.list_values, args=(4,), name="count")
worker.start()
worker.join()count prints [1, 2, 3, 4]. self is still the Board instance. args holds only m, because self is already bound on board.list_values. The steps match the function approach, with a method in place of a plain function.
Key takeaways
-
The second approach puts the child's logic in a method
-
targetcan beinstance.method -
selfstays the instance;argsholds the remaining parameters -
Create the object before you create the
Thread -
start()still dispatches the child -
Next: Join and Status —
is_alive()andjoin() -
Previous: Function Threads
Loading playground…
Check your understanding
Class Threads Quiz
In the class approach, where does the child's logic live?
1 / 10