the usage of target in Python

In Python, the ‘target’ parameter is optional and is used to specify the function to be executed when creating a thread.

Here is an example of how to use Target in Python.

  1. Create a basic thread.
import threading

def print_name():
    print("Hello, World!")

thread = threading.Thread(target=print_name)
thread.start()
  1. Passing parameters to the thread function:
import threading

def print_name(name):
    print("Hello, " + name + "!")

thread = threading.Thread(target=print_name, args=("Alice",))
thread.start()
  1. Using a lambda expression as the thread function:
import threading

thread = threading.Thread(target=lambda: print("Hello, World!"))
thread.start()
  1. Implementing a class method as a thread function.
import threading

class MyThread(threading.Thread):
    def run(self):
        print("Hello, World!")

thread = MyThread()
thread.start()

It is important to note that the target parameter can only accept one callable object, such as a function, lambda expression, or method of a class. If you need to pass multiple parameters, you can use args or kwargs parameters to pass the arguments.

bannerAds