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()
Python函数嵌套与装饰器应用
文章探讨了Python中的函数嵌套,展示了如何使用`nonlocal`关键字修改外部函数的变量。此外,还介绍了装饰器的概念,提供了装饰器的基本写法和另一种写法,用例中装饰器用于在函数执行前后添加特定行为。
1069

被折叠的 条评论
为什么被折叠?



