【Python3】装饰器

定义:

装饰本质是函数,装饰其他函数。为其他函数添加附加功能。高阶+嵌套=装饰器

原则:

  1. 不能修改被装饰函数的源代码
  2. 不能修改被装饰函数的调用方式

知识储备:

  1. 函数即‘变量’(函数名相当于变量名,函数体相当于变量值)
  2. 高阶函数
  3. 嵌套函数

格式:

def deco_name(func):
    def deco(*args,**kwargs)
       func(*args,**kwargs)
       功能B
    return deco

@add #raw_func=deco_name(raw_func)
def raw_func(): 功能A
raw_finc()

示例:

import time
def count_time(func)
   def deco()
       start_time=time.time()
       func()
       stop_time=time.time()
       print('the time is %s'%(start_time-stop_time)) 
   return deco
@count_time
def suspend(): time.sleep(3) print('延迟三秒后输出这句话)


suspend()
原文地址:https://www.cnblogs.com/shengxinjack/p/7746355.html