python theading.Timer:如何将参数传递给回调?

Bin*_*hen 28 python timer

我的代码:

    import threading

def hello(arg, kargs):
    print arg

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

while 1:
    pass
Run Code Online (Sandbox Code Playgroud)

打印输出只是:

b
Run Code Online (Sandbox Code Playgroud)

如何将参数传递给回调?kargs是什么意思?

Gle*_*ard 53

Timer 获取一个参数数组和一个关键字参数的字典,因此您需要传递一个数组:

import threading

def hello(arg):
    print arg

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

while 1:
    pass
Run Code Online (Sandbox Code Playgroud)

你看到"b"是因为你没有给它一个数组,所以它对待"bb"一个可迭代的; 它基本上就像你给它一样["b", "b"].

kwargs 用于关键字参数,例如:

t = threading.Timer(2, hello, ["bb"], {arg: 1})
Run Code Online (Sandbox Code Playgroud)

有关关键字参数的信息,请参见http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html.


out*_*tis 5

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

t = threading.Timer(2, hello, ["bb"])
Run Code Online (Sandbox Code Playgroud)

据推测,hello其目的是具有如下参数:

def hello(*args, **kwargs):
Run Code Online (Sandbox Code Playgroud)

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