如何将参数传递给 threading.Timer 回调?
我尝试了这段代码:
import threading
def hello(arg, kargs):
print(arg)
t = threading.Timer(2, hello, "bb")
t.start()
while 1:
pass
输出只是 b
而不是 bb
。
如何正确地将参数传递给回调?
如果我从 hello
中删除 kargs
参数,我会收到一个异常,提示 TypeError: hello() gets 1positional argument but 2 were returned
。为什么?第一个代码中的 kargs 值来自哪里?
I tried this code:
import threading
def hello(arg, kargs):
print(arg)
t = threading.Timer(2, hello, "bb")
t.start()
while 1:
pass
The output is just b
instead of bb
.
How can I pass arguments to the callback properly?
If I remove the kargs
parameter from hello
, I get an exception that says TypeError: hello() takes 1 positional argument but 2 were given
. Why? Where did the kargs
value come from in the first code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Timer
需要一个参数序列(通常是列表或元组)和关键字参数的映射(通常是字典),因此传递一个列表:因为
"bb"
是一个可迭代对象,Timer
将迭代它并使用每个元素作为单独的参数;threading.Timer(2, hello, "bb")
相当于threading.Timer(2, hello, ["b", "b"])
。使用字典将任何 关键字参数 传递给回调,例如:
Timer
expects a sequence (normally, a list or tuple) of arguments and a mapping (normally, a dict) of keyword arguments, so pass a list instead:Since
"bb"
is an iterable, theTimer
will iterate over it and use each element as a separate argument;threading.Timer(2, hello, "bb")
is equivalent tothreading.Timer(2, hello, ["b", "b"])
.Use a dictionary to pass any keyword arguments to the callback, for example:
Timer 的第三个参数是一个序列。将
"bb"
作为该序列传递意味着hello
获取该序列的元素("b"
和"b")作为单独的参数(
arg
和kargs
)。将"bb"
放入列表中,hello
会将字符串作为第一个参数:据推测,
hello
的参数如下:有关详细说明,请参阅**(双星/星号)和*(星号/星号)对参数有何作用?句法。
The third argument to
Timer
is a sequence. Passing"bb"
as that sequence means thathello
gets the elements of that sequence ("b"
and"b"
) as separate arguments (arg
andkargs
). Put"bb"
in a list, andhello
will get the string as the first argument:Presumably,
hello
was intended to have parameters like:See What does ** (double star/asterisk) and * (star/asterisk) do for parameters? for a detailed explanation of this syntax.