2011-03-05 81 views
1

爲什麼這段代碼不起作用?python裝飾器,調用延遲功能

from threading import Timer 

def delayed(seconds): 
    def decorator(f): 
     def wrapper(*args, **kargs): 
      Timer(seconds, f, args, kargs) 
     return wrapper 
    return decorator 

@delayed(1) 
def foo(): 
    '''this function does not return''' 
    print('foo') 

foo() 
print('dudee') 

我只是這樣的結果: dudee 富

我只有 dudee

回答

5

因爲你沒有啓動計時器嘗試這樣的:

from threading import Timer 

def delayed(seconds): 
    def decorator(f): 
     def wrapper(*args, **kargs): 
      t = Timer(seconds, f, args, kargs) 
      t.start() 
     return wrapper 
    return decorator 

@delayed(1) 
def foo(): 

    print('foo') 

foo() 
print('dudee') 
+0

OHU神!我在沒有實例化的情況下檢查dir(Timer)!謝謝! – nkint 2011-03-06 12:12:06