装饰器、生成器

一、装饰器
1. 本质是函数,用来装饰其他函数,就是为其他函数添加附加功能。
2.原则:1.不能修改被装饰函数的源代码。2.不能修改被装饰函数的调用方式。
实现装饰器知识储备:
1.函数即“变量”
2.高阶函数
高阶函数满足的两个条件:
a.把一个函数名当成实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
b.返回值中包含函数名(不能修改被装饰函数的调用方式)
3.嵌套函数
高阶函数+嵌套函数--》装饰器
例子:
import time
def timer(func):
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time=time.time()
print("the func run time is:%s"%(stop_time-start_time))
return deco
@timer #test1=timer(test1)
def test1(x,y):
time.sleep(3)
print("in test1")
@timer
def test2():
time.sleep(2)
print("in the test2")
x=1
y=2
test1(x,y)
test2()

二、生成器
# 1.生成器只有在调用时才会生成相应的数据
# 2.只记录当前位置
# 3.只有一个_next_()方法
例1:
def fib(max):

n,a,b=0,0,1
while n<max:
# print(b)
yield b
a,b=b,a+b
n+=1
return "-----done------"
f=fib(5)
while True:
try:
x=next(f)
print("f:",x)
except StopIteration as e:
print("Generator return value:",e.value)
break
f.__next__()
f.__next__()
f.__next__()
f.__next__()
f.__next__()

例2:
import time

def consumer(name):
print("%s 准备吃包子啦!" % name)
while True:
baozi = yield "a"
print("包子[%s]来了,被[%s]吃了!" % (baozi, name))
c=consumer("deng")
c.__next__()
c.__next__()
c.__next__()
c.__next__()

def producer(name):
c = consumer('A')
c2 = consumer('B')
c.__next__()
c2.__next__()
print("老子开始准备做包子啦!")
for i in range(1,10):
time.sleep(1)
# print("做了2个包子!")
c.send(i)
c2.send(i)

producer("")
三、内置函数
1.compile()的特殊用途,可以将一段代码code,
py_obj=compile(code,"err.log","exec")
exec(py_obj)
相当于import导入模块。

或者用exec(code)也相当于import导入模块。
 
原文地址:https://www.cnblogs.com/knighterrant/p/9383945.html