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)


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


猜你喜欢

转载自blog.51cto.com/12182612/2471170