总结十一
一.闭包函数
闭包函数:内部引用了外部函数里定义的对象,这样就可以成为闭包函数
闭包函数的两个要求:
1.定义在函数内部的函数
2.内部函数引用了外部函数作用域的名字
def outer(): x = 111 def inner(): print(): return inner res = outer() # res就是inner函数的内存地址 def func(): x = 222 res() func()
给函数体传值的两种方式:
第一种:传参
def index(username):
print(username)
第二种:闭包
def outer(x,y):
def my_max():
if x > y:
return x
return y
res = outer(1,2) # res就是my_max函数的内存地址
print(res())
二.装饰器
装饰器:英语拓展原来函数功能的一种函数,目的是在不改变原函数名的情况下,给函数增加新的功能
装饰器的原则:开发封闭原则
1.对拓展开放
2.对修改封闭
装饰器必须遵守的两个原则:
1.不可改变被装饰对象源代码
2.不可改变被装饰对象调用方式
可调用:callable 可以加括号执行
def index():
pass
index()
import time
获取时间戳(秒) time.time 当前时间举例1970.1.1 00:00:00(Unix诞生元年)所过去的秒数
time.sleep(second) 括号中的数字表示暂停几秒执行
装饰器语法糖:会将紧挨着他的可调用对象的名字当做参数自动传入调用
语法糖在书写的是要,要与被装饰对象紧紧挨着,两者之间不要有空格
from functools import wraps def outer(func): @wraps(func) def inner(*args,**kwargs): # * ** 在形参中使用 # 执行被装饰函数之前你可以做的操作 res = func(*args,**kwargs) # * ** 在实参中使用 return res return inner @outer def index(username,*args,**kwargs): """index注释""" pass print(index) <function index at 0x000001E87F03F1E0>
装饰器修复技术
1.返回原来函数的函数名
2.返回原来函数的注释
def wrappers(data): def outer(func): def inner(*args,**kwargs): if data == 'file': # 执行被装饰函数之前你可以做的操作 res = func(*args,**kwargs) # * ** 在实参中使用 # 执行被装饰函数之后你可以做到的操作 return res return res return outer
装饰器的嵌套
1.装饰器在装饰的时候,顺序是从下往上的
2.装饰器在执行的时候,顺序是从上往下的
def outter1(func1): print('加载了outter1') def wrapper1(*args,**kwargs): print('执行了wrapper1') res1 = func1(*args,**kwargs) return res1 return wrapper1 def outter2(func2): print('加载了outter2') def wrapper2(*args,**kwargs): print('执行了wrapper2') res2 = func2(*args,**kwargs) return res2 return wrapper2 def outter3(func3): print('加载了outter3') def wrapper3(*args,**kwargs): print('执行了wrapper3') res3 = func3(*args,**kwargs) return res3 return wrapper3 @outter1 @outter2 @outter3 def index(): print('from index') index()