2014-09-23 97 views
-1

我想將值列表傳遞給裝飾器。裝飾器裝飾的每個函數都會傳遞不同的值列表。我現在用的是decorator Python庫將參數傳遞給裝飾器

這裏是我試圖 -

from decorator import decorator 
def dec(func, *args): 
    // Do something with the *args - I guess *args contains the arguments 
    return func() 

dec = decorator(dec) 

@dec(['first_name', 'last_name']) 
def my_function_1(): 
    // Do whatever needs to be done 

@dec(['email', 'zip']) 
def my_function_2(): 
    // Do whatever needs to be done 

但是,這是行不通的。它給出了一個錯誤 - AttributeError: 'list' object has no attribute 'func_globals'

我該怎麼做?

+0

https://stackoverflow.com/questions/5929107/python-decorators-with-parameters – 2014-09-23 14:09:17

回答

0

可以實現它沒有裝飾庫

def custom_decorator(*args, **kwargs): 
    # process decorator params 
    def wrapper(func): 
     def dec(*args, **kwargs): 
      return func(*args, **kwargs) 
     return dec 
    return wrapper 

@custom_decorator(['first_name', 'last_name']) 
def my_function_1(): 
    pass 
@custom_decorator(['email', 'zip']) 
def my_function_2(): 
    pass 
+0

這很酷。無論如何,這可以用'decorator'庫實現嗎? – Siddharth 2014-09-23 14:09:10