天天看點

python的裝飾器了解

    之前在學習flash的時候用到過python的裝飾器,但是卻不知道具體的原理,特此花費一些時間學習 一下裝飾器的知識。

1.裝飾器就是python的函數,使用方式: @函數的名稱

    簡單的就是把一個函數作為參數傳遞給另外一個函數,是以另外的使用方式: 函數1 = 函數2(函數3)

2.一個不帶參數的裝飾器并使用: @函數名

不帶參數的裝飾器

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)      
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      

繼續閱讀