python 装饰器

139 阅读1分钟

装饰器(Decorators)是 Python 的一个重要部分。简单地说:他们是修改其他函数的功能的函数。为其他函数添加附加功能,不改变原函数代码及调用方式

创建装饰器

# 定义一个接收函数的方法,在此方法内创建一个函数,并返回该函数
def a_decorators(a_function): 
    def my_decorators_func():
        print("I am doing some boring work before executing my_decorators_func()")
        a = a_function()
        print("I am doing some after work before executing my_decorators_func()")
        return a
    return my_decorators_func

使用wraps修饰

from functools import wraps
def a_decorators(a_function): 
    @wraps(a_function)
    def my_decorators_func():
        print("I am doing some boring work before executing my_decorators_func()")
        a = a_function()
        print("I am doing some after work before executing my_decorators_func()")
        return a
    return my_decorators_func

使用装饰器

用法1
@a_decorators
def do_some_thing():
    ...
用法2
a_new_func = a_decorators(do_some_thing)
a_new_func()

带参数的装饰器

def a_decorators_args(flag=True):
    def a_decorators(a_function):
        def my_decorators_func(name):
            if flag:
                print("I am doing some boring work before executing a_function()")
            a = a_function(name)
            print("I am doing some after work after executing a_function()")
            return a
        return my_decorators_func
    return a_decorators


@a_decorators_args(False)
def a_function(name):
    print(name)

if __name__ == '__main__':
    a_function('bai')

使用场景

授权(Authorization)
from functools import wraps 
def requires_auth(f): 
    @wraps(f)
    def decorated(*args, **kwargs): 
        auth = request.authorization 
        if not auth or not check_auth(auth.username, auth.password): 
            authenticate() 
        return f(*args, **kwargs) 
    return decorated
日志(Logging)

`

from functools import wraps


def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)

    return with_logging


@logit
def addition_func(x):
    """Do some math."""
    return x + x


result = addition_func(4)

`