python threading怎么传参
时间: 2023-11-11 14:07:03 浏览: 75
在Python中,可以通过以下方式在线程中传递参数:
1. 使用threading.Thread对象的args参数来传递一个元组。例如:
```
import threading
def my_function(arg1, arg2):
print(arg1, arg2)
my_thread = threading.Thread(target=my_function, args=("Hello", "World"))
my_thread.start()
```
2. 使用threading.Thread对象的kwargs参数来传递一个字典。例如:
```
import threading
def my_function(arg1, arg2):
print(arg1, arg2)
my_thread = threading.Thread(target=my_function, kwargs={"arg1": "Hello", "arg2": "World"})
my_thread.start()
```
3. 继承threading.Thread并实现__init__方法来传递自定义参数。例如:
```
import threading
class MyThread(threading.Thread):
def __init__(self, arg1, arg2):
threading.Thread.__init__(self)
self.arg1 = arg1
self.arg2 = arg2
def run(self):
print(self.arg1, self.arg2)
my_thread = MyThread("Hello", "World")
my_thread.start()
```
阅读全文