python闭包与装饰器
'''
两句口诀理解闭包与装饰器
1.闭包:至少两层楼,楼下变量管上楼,return上楼不动手
2.装饰器:客人空手来,还得请上楼,干啥都同意,有参给上楼
'''
def secondFloor(func):
def thirdFloor():
print('源函数开始执行了')
func()
print('源函数执行完了')
return thirdFloor
def orign():
print('我是源函数')
sf = secondFloor(orign)
sf()
'python中的语法糖'
@secondFloor
def orign():
print('我是源函数')
orign()
# 这两种调用方法结果是一样的
被装饰的函数带参数
def secondFloor(func):
def thirdFloor(arg):
print('源函数开始执行了')
func(arg)
print('源函数执行完了')
return thirdFloor
@secondFloor
def orign(info):
print(info)
info = '你好啊'
orign(info)
被装饰的函数带参数二:
import time def calculate_time(f): def inner(*args,**kwargs): start_time = time.time() ret = f(*args,**kwargs) end_time = time.time() print(end_time - start_time) return ret return inner @calculate_time def add(m,n): time.sleep(2.2) return m+n f = add(5,7) print(f)