装饰器底层原理基于【闭包】,而闭包底层原理基于【Python嵌套函数】:
- nonlocal
- global
- 注意上述两种变量类型的使用情况
- Python - global类型与globals()方法
-
Python装饰器通过@符号标志,其本质上是一个函数
-
装饰器放在一个函数的前面,表名对该函数进行“装饰”
- 装饰器将其后方的函数作为自己的参数,通过自己内部的逻辑进行加工( 返回一个新的函数对象 )
实例(闭包、装饰器与协程):
def coroutine(func):
def start(*args,**kwargs):
g = func(*args,**kwargs)
print("*")
g.__next__()
return g
return start
@coroutine
def line_splitter(delimiter=None):
print("Ready to split")
result = None
while True:
line = (yield result)
result = line.split(delimiter)
a = line_splitter(",")
print(a.send("4,1,2,5,3"))
print(a.send("A,B,C,D,E"))
a.close()
作用(日志记录):
在指定函数执行前对该函数进行修改或在该函数之前执行和该函数相关的某些操作(日志);
def log(func):
import time
def a0(*args,**kwargs):
b = func(*args,**kwargs)
tt = time.ctime
log_file = "C:\\Users\\Clipse\\Desktop\\log.txt"
with open(log_file,"a") as f:
content_0 = __file__+"\n"
content_1 = b.__name__+"() was called on "+str(tt())+"\n"
content_2 = "*"*60+"\n"
f.write(content_0)
f.write(content_1)
f.write(content_2)
return b
return a0
@log
def demo():
result = 99
while True:
data = (yield result)
print(data,"??")
a = demo()
a.__next__()
print(a.send(10))
print(a.send(30))
a.close()
附加:协程的执行过程分析