以前在學習flash的時候用到過python的裝飾器,可是殊不知道具體的原理,特此花費一些時間學習 一下裝飾器的知識。
python
1.裝飾器就是python的函數,使用方式: @函數的名稱bash
簡單的就是把一個函數做爲參數傳遞給另一個函數,因此另外的使用方式: 函數1 = 函數2(函數3)
app
2.一個不帶參數的裝飾器並使用: @函數名ide
不帶參數的裝飾器函數
def myfunc(func): print("myfunc before") func() print("myfunc after") @myfunc def funcs(a): print("this is funcs") funcs() # 在調用funcs函數時,就會先把funcs函數地址傳遞給 myfunc函數的func,執行func的動做就至關於執行funcs函數 ------------------------------------------------------------- 裝飾器函數引用被裝飾函數的參數案例 def myfunc(func): def warpper(*args,**kwargs) # *args, **kwargs用於接收func的參數 warpper函數和funcs的函數地址是同樣的 print("myfunc before") func(*args,**kwargs) print("myfunc after") @myfunc def funcs(a): print(a) funcs(1)
3.帶參數的裝飾器: @函數名("","")學習
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2): print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2 def my_decorator(func): # 這裏傳遞參數的能力是借鑑了 closures. # 若是對closures感到困惑能夠看看下面這個: # http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2 # 不要忘了裝飾器參數和函數參數! def wrapped(function_arg1, function_arg2) : print ("I am the wrapper around the decorated function.\n" "I can access all the variables\n" "\t- from the decorator: {0} {1}\n" "\t- from the function call: {2} {3}\n" "Then I can pass them to the decorated function" .format(decorator_arg1, decorator_arg2, function_arg1, function_arg2)) return func(function_arg1, function_arg2) return wrapped return my_decorator @decorator_maker_with_arguments("Leonard", "Sheldon") def decorated_function_with_arguments(function_arg1, function_arg2): print ("I am the decorated function and only knows about my arguments: {0}" " {1}".format(function_arg1, function_arg2)) decorated_function_with_arguments("Rajesh", "Howard") #輸出: #I make decorators! And I accept arguments: Leonard Sheldon #I am the decorator. Somehow you passed me arguments: Leonard Sheldon #I am the wrapper around the decorated function. #I can access all the variables # - from the decorator: Leonard Sheldon # - from the function call: Rajesh Howard #Then I can pass them to the decorated function #I am the decorated function and only knows about my arguments: Rajesh Howard