python杂记-5(装饰器)

1、被装饰的函数有参数(一个参数):

def w1(func):
    def inner(arg):
        # 验证1
        # 验证2
        # 验证3
        return func(arg)
    return inner

@w1
def f1(arg):
    printf1)

2、被装饰的函数有参数(两个参数):

def w1(func):
    def inner(arg1,arg2):
        # 验证1
        # 验证2
        # 验证3
        return func(arg1,arg2)
    return inner

@w1
def f1(arg1,arg2):
print(f1)
 

3、被装饰的函数有参数(三个参数):

def w1(func):
    def inner(arg1,arg2,arg3):
        # 验证1
        # 验证2
        # 验证3
        return func(arg1,arg2,arg3)
    return inner

@w1
def f1(arg1,arg2,arg3):
    printf1)

4、装饰具有处理n个参数的函数的装饰器:

def w1(func):
    def inner(*args, **kwargs):
        # 验证1
        # 验证2
        # 验证3
        return func(*args, **kwargs)

    return inner


@w1
def f1(arg1, arg2, arg3):
    print(f1)

5、一个函数可以被多个装饰器装饰:

def w2(func):
    def inner(*args, **kwargs):
        # 验证1
        # 验证2
        # 验证3
        return func(*args, **kwargs)

    return inner


@w1
@w2
def f1(arg1, arg2, arg3):
    print(f1)

6、更牛逼的装饰器:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def Before(request, kargs):
    print('before')


def After(request, kargs):
    print('after')


def Filter(before_func, after_func):
    def outer(main_func):
        def wrapper(request, kargs):

            before_result = before_func(request, kargs)
            if (before_result != None):
                return before_result;

            main_result = main_func(request, kargs)
            if (main_result != None):
                return main_result;

            after_result = after_func(request, kargs)
            if (after_result != None):
                return after_result;

        return wrapper

    return outer


@Filter(Before, After)
def Index(request, kargs):
    print('index')

7、functools.wraps

上述的装饰器虽然已经完成了其应有的功能,即:装饰器内的函数代指了原函数,注意其只是代指而非相等,原函数的元信息没有被赋值到装饰器函数内部。例如:函数的注释信息

def outer(func):
    def inner(*args, **kwargs):
        print(inner.__doc__)  # None
        return func()
    return inner

@outer
def function():
    """
    asdfasd
    :return:
    """
    print('func')

如果使用@functools.wraps装饰装饰器内的函数,那么就会代指元信息和函数。

def outer(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        print(inner.__doc__)  # None
        return func()
    return inner

@outer
def function():
    """
    asdfasd
    :return:
    """
    print('func')

 

posted @ 2016-11-02 15:38  闹P丫你  阅读(186)  评论(0编辑  收藏  举报