Python入门:装饰器

装饰器:本质是函数,(功能:装饰其他函数),也就是为其他函数添加附加功能

原则:1.不能修改被装饰的函数的源代码

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

实现装饰器知识储备:

1.函数即“变量”

2.高阶函数

         a:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

          b:返回值中包含函数名(不修改调用函数的方式)

3.嵌套函数

高阶函数+嵌套函数=》装饰器

例子(满足第一个原则):

import time

def bar():

  time.sleep(3)

  print("in the bar ")

def test1(func):

  start_time=time.time()

  func() # run bar

  stop_time=time.time()

  print("the func run time is %s" %(stop_time-start_time))

test1(bar)

例子2(满足原则2):

import time

def bar():

  time.sleep(3)

  print("in the bar ")

def test2(func):

  print(func)

  return func

t=test2(bar)

t()

原文地址:https://www.cnblogs.com/luckerzhang/p/9289985.html