共計(jì) 652 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Python 中,target
是一個(gè)可選參數(shù),用于指定在創(chuàng)建線程時(shí)要運(yùn)行的函數(shù)。
以下是 target
在 Python 中的用法示例:
- 創(chuàng)建一個(gè)簡(jiǎn)單的線程:
import threading
def print_name():
print("Hello, World!")
thread = threading.Thread(target=print_name)
thread.start()
- 將參數(shù)傳遞給線程函數(shù):
import threading
def print_name(name):
print("Hello, " + name + "!")
thread = threading.Thread(target=print_name, args=("Alice",))
thread.start()
- 使用 lambda 表達(dá)式作為線程函數(shù):
import threading
thread = threading.Thread(target=lambda: print("Hello, World!"))
thread.start()
- 使用類的方法作為線程函數(shù):
import threading
class MyThread(threading.Thread):
def run(self):
print("Hello, World!")
thread = MyThread()
thread.start()
需要注意的是,target
參數(shù)只能接受一個(gè)可調(diào)用對(duì)象,例如函數(shù)、lambda 表達(dá)式或類的方法。如果要傳遞多個(gè)參數(shù),可以使用 args
或 kwargs
參數(shù)來傳遞參數(shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完