闭包代码:
# 闭包定义:内部函数引用外部变量
# 闭包实现计数器
def counter(FIRST=0): # FIRST=0 表示传入值从FIRST开始,不传值就从0开始
cnt = [FIRST]
def counter1():
cnt[0] += 1
return cnt[0]
return counter1 # 返回时不能带括号,比如return counter1()
num5 = counter(5)
num10 = counter(10)
print(num5())
print(num5())
print(num5())
print(num10())
print(num10())
print(num10())
装饰器代码:
#装饰器与闭包的区别就是装饰器传的函数,而闭包传的是变量
def timer(func):
def cha_timer():
start_time = time.time()
func()
stop_time = time.time()
print('时间差是 %s 秒 '%(stop_time - start_time))
return cha_timer
@timer
def i_can_sleep():
time.sleep(3)
i_can_sleep
装饰器的使用:
#装饰器的使用
def new_shuxue(argv):
def shuxue(func):
def jiafa(a,b):
print('执行函数%s %s'%(argv,func.__name__))
func(a,b)
print('stop')
return jiafa
return shuxue
@new_shuxue('为') #该处不能忘记加参数:('为')
def add(a,b):
print(a+b)
print(add(4,5))
迭代代码:
# yield 迭代(用于需要自己构建时)
def frange(start,stop,step):
x = start
while x < stop:
yield x
x += step
for i in frange(10,20,0.5):
print(i)