如何将参数传递给 threading.Timer 回调?

发布于 2024-10-06 19:23:53 字数 405 浏览 0 评论 0原文

我尝试了这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

佞臣 2024-10-13 19:23:53

Timer 需要一个参数序列(通常是列表或元组)和关键字参数的映射(通常是字典),因此传递一个列表:

import threading

def hello(arg):
    print(arg)

t = threading.Timer(2, hello, ["bb"])
t.start()

while 1:
    pass

因为 "bb" 是一个可迭代对象,Timer 将迭代它并使用每个元素作为单独的参数; threading.Timer(2, hello, "bb") 相当于 threading.Timer(2, hello, ["b", "b"])

使用字典将任何 关键字参数 传递给回调,例如:

def hello(arg, kwarg):
    print('arg is', arg, 'and kwarg is', kwarg)

t = threading.Timer(2, hello, ["bb"], {'kwarg': 1})

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:

import threading

def hello(arg):
    print(arg)

t = threading.Timer(2, hello, ["bb"])
t.start()

while 1:
    pass

Since "bb" is an iterable, the Timer will iterate over it and use each element as a separate argument; threading.Timer(2, hello, "bb") is equivalent to threading.Timer(2, hello, ["b", "b"]).

Use a dictionary to pass any keyword arguments to the callback, for example:

def hello(arg, kwarg):
    print('arg is', arg, 'and kwarg is', kwarg)

t = threading.Timer(2, hello, ["bb"], {'kwarg': 1})
鹿港巷口少年归 2024-10-13 19:23:53

Timer 的第三个参数是一个序列。将 "bb" 作为该序列传递意味着 hello 获取该序列的元素("b""b")作为单独的参数(argkargs)。将 "bb" 放入列表中,hello 会将字符串作为第一个参数:

t = threading.Timer(2, hello, ["bb"])

据推测,hello 的参数如下:

def hello(*args, **kwargs):

有关详细说明,请参阅**(双星/星号)和*(星号/星号)对参数有何作用?句法。

The third argument to Timer is a sequence. Passing "bb" as that sequence means that hello gets the elements of that sequence ("b" and "b") as separate arguments (arg and kargs). Put "bb" in a list, and hello will get the string as the first argument:

t = threading.Timer(2, hello, ["bb"])

Presumably, hello was intended to have parameters like:

def hello(*args, **kwargs):

See What does ** (double star/asterisk) and * (star/asterisk) do for parameters? for a detailed explanation of this syntax.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文