我的代碼:python theading.Timer:如何將參數傳遞給回調函數?
import threading
def hello(arg, kargs):
print arg
t = threading.Timer(2, hello, "bb")
t.start()
while 1:
pass
打印出來放就是:
b
我如何可以傳遞參數給回調? kargs是什麼意思?
我的代碼:python theading.Timer:如何將參數傳遞給回調函數?
import threading
def hello(arg, kargs):
print arg
t = threading.Timer(2, hello, "bb")
t.start()
while 1:
pass
打印出來放就是:
b
我如何可以傳遞參數給回調? kargs是什麼意思?
Timer
需要的參數數組和關鍵字參數的字典,所以你需要傳遞一個數組:
import threading
def hello(arg):
print arg
t = threading.Timer(2, hello, ["bb"])
t.start()
while 1:
pass
你看到「B」,因爲你不給它一個數組,所以它將"bb"
視爲可迭代的;它本質上就像你給它["b", "b"]
。
kwargs
是關鍵字參數,如:
t = threading.Timer(2, hello, ["bb"], {arg: 1})
有關的關鍵字參數信息,請參閱http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html。
Timer
的第三個參數是一個序列。由於您將「bb」作爲該序列傳遞,因此hello
會將該序列的元素(「b」和「b」)作爲單獨的參數(arg
和kargs
)獲取。將「bb」放在列表中,hello
將獲得字符串作爲第一個參數。
t = threading.Timer(2, hello, ["bb"])
至於hello
的參數,你大概的意思是:
def hello(*args, **kwargs):
的**kwargs
含義是包括在queston‘What does *args and **kwargs mean?’
這裏有關鍵字參數的鏈接[第](http://docs.python.org/tutorial/controlflow.html#keyword-arguments)在一個更新版本的教程中(儘管信息看起來差不多)。 – martineau 2010-12-11 09:26:21
谷歌不斷在這個版本中讓我失望。具有諷刺意味的是,舊版本更易於閱讀;他們已經走到了盡頭,造型更新,令人分心,背景顏色來回跳動。 – 2010-12-11 19:19:43