def outer(logo):
def inner(msg):
print(f"{logo}{msg}{logo}")
return inner # 返回值是一个函数
f1 = outer("奥") # f1是一个函数
f1("利")
修改外部函数的值:nonlocal
def outer(nub1):
def inner(nub2):
nonlocal nub1 # 通过nonlocal使我们可以修改nub1
nub1 += nub2
print(nub1)
return inner
f1 = outer(10)
f1(20)
装饰器:(也是闭包)
基础写法:
另一种写法: (其中func代表一个函数)
def sleep():
import random
import time
print("睡眠中。。。")
time.sleep(random.randint(1,5))
# 装饰器的一般写法
def outer(func):
def inner():
print("我要睡觉了")
sleep()
print("wake")
return inner
fn = outer(sleep)
fn()