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

2024-05-14 17:59:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

    import threading

def hello(arg, kargs):
    print arg

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

while 1:
    pass

打印出来的只是:

b

如何向回调传递参数?卡格斯是什么意思?


Tags: 代码importhello参数defargpassstart
2条回答

Timer接受一个参数数组和一个关键字参数dict,因此需要传递一个数组:

import threading

def hello(arg):
    print arg

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

while 1:
    pass

你看到“b”是因为你没有给它一个数组,所以它把"bb"看作一个iterable;本质上就像你给它["b", "b"]

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

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

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

Timer的第三个参数是一个序列。由于将“b b”作为该序列传递,hello将该序列的元素(“b”和“b”)作为单独的参数(argkargs)。将“bb”放在列表中,hello将得到字符串作为第一个参数。

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

至于hello的参数,您可能是指:

def hello(*args, **kwargs):

**kwargs的含义包含在queston“What does *args and **kwargs mean?”中

相关问题 更多 >

    热门问题