装饰器 高阶函数 函数闭包

1.装饰器

本质是函数,功能是为其他函数添加附加功能

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

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

  装饰器=高阶函数+函数嵌套+闭包

#装饰器格式框架
def wrap(func):
def wrapper(*args,**kwargs):
func(*args,**kwargs)
return wrapper

2.高阶函数

含义:1.函数接受参数的是一个函数

           2.函数返回值是一个函数

           3.满足上面任一条件都是高阶函数

# 高阶函数
import time

def hello():
time.sleep(3)
print('hello world')

def timer(func):
start_time = time.time()
func()
end_time = time.time()
print('函数运行时间是:%s' % (end_time - start_time))
return func


t = timer(hello)
t()

# 装饰器写法
def total_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
res = func(*args, **kwargs)
stop_time = time.time()
print("函数运行时间:%s" %(stop_time-start_time))
return res
return wrapper

# @后面装饰器 作用于下面 相对于hello = total_time(hello)
@total_time
def hello():
time.sleep(2)
print("hello world")
  return "hello"

h = hello()
print(h)

#显示
# hello world
# 函数运行时间:2.000795364379883
# 2.000795364379883



猜你喜欢

转载自www.cnblogs.com/icemonkey/p/10439702.html