如何写装饰器

函数装饰器,可以在不改变原来的函数的情况下,在原来的函数的前面或者后面添加动作。

Do something before

原来的函数动作

Do something after

 基本流程如下:

1. 首先定义要添加的功能函数

def 装饰的函数(参数,此参数用来传入正常函数的函数名)

  def WraptheFunction()

    do something before

    参数()

    do something after

  retrun WraptheFunc

注意此次 return 的函数名,不带() 

2. def 正常工作的函数()

  正常函数的动作

3. 在正常函数之前添加

  @ 装饰的函数

def a_new_func(func_name)
    def WraptheFunc()
        print"do something before"func_name()
        print("do something after")
    return WraptheFunc


@a_new_func

def normal_func():
    print("I am working normal...")


normal_func()

 1. 遇到 @ a_new_func,把@下面的函数名(normal_func)作为参数传入到 a_new_func中去。即 “normal_func” ----> “func_name”

2. 把装饰器中定义的函数名去代替被装饰函数的函数名。即"WraptheFunc"  ---> "normal_func"

 

装饰器使用蓝本:

注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not can_run:
            return "Function will not run"
        return f(*args, **kwargs)
    return decorated
 
@decorator_name
def func():
    return("Function is running")
 
can_run = True
print(func())
# Output: Function is running
 
can_run = False
print(func())
# Output: Function will not run
原文地址:https://www.cnblogs.com/xuwenwei/p/14306857.html