我想在创建Thread对象时向目标函数传递命名参数。
以下是我编写的代码:
import threading
def f(x=None, y=None):
print x,y
t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()
我在第6行的"x=1"处遇到了语法错误。 我想知道如何将关键字参数传递给目标函数。
我想在创建Thread对象时向目标函数传递命名参数。
以下是我编写的代码:
import threading
def f(x=None, y=None):
print x,y
t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()
我在第6行的"x=1"处遇到了语法错误。 我想知道如何将关键字参数传递给目标函数。
t = threading.Thread(target=f, kwargs={'x': 1,'y': 2})
这将通过将关键字参数名称作为字典的键和参数值作为字典中的值来传递字典。
上面的另一个答案不起作用,因为该范围内未定义"x"和"y"。
另一个例子,这次使用多进程,同时传递位置参数和关键字参数:
使用的函数是:
def f(x, y, kw1=10, kw2='1'):
pass
然后当使用多进程调用时:
p = multiprocessing.Process(target=f, args=('a1', 2,), kwargs={'kw1': 1, 'kw2': '2'})
import threading
def f(x=None, y=None):
print x,y
my_dict = {'x':1, 'y':2}
t = threading.Thread(target=f, kwargs=my_dict)
t.start()
kwargs={x: 1, y: 2}
替换args
。{'x': 1, 'y': 2}
,这是一个很大的差别。 - glglgl
t = threading.Thread(target=f, args=(1,2,))
。 - bonh