# python的嵌套函数和闭包

40 篇文章 4 订阅

### 嵌套函数

1.如果在一个函数内部定义了另一个函数，我们称外部的函数为外函数，内部的函数为内函数

def testfunc():
def func1():
return "This is func1"
def func2():
return "This is func2"

print(func1())
print(func2())
print("Now you are back in testfunc()")
testfunc()

This is func1
This is func2
Now you are back in testfunc()


testfunc1()和testfunc2()在函数testfunc()之外是不能访问的。

NameError: name ‘func1’ is not defined

2.内函数访问外函数的变量

def outer_func(a):
b = 1
c = [a]

def inner_func():
nonlocal b
b += 1
c[0] += 1
print(c[0], b)

inner_func()

if __name__ == '__main__':
outer_func(5)



3.嵌套函数的使用场景

def outer_func():
return a + b

x, y = 1, 2
print(z)

if __name__ == '__main__':
outer_func()



### 闭包

1.闭包的使用

def testfunc(n):
print("Now you are in testfunc()")
def func1():
return "This is func1"
def func2():
return "This is func2"
return func1 if n==1 else func2
tt=testfunc(1)
print(tt)
print(tt())
#Now you are in testfunc()
#<function testfunc.<locals>.func1 at 0x000001FDE78EBCA8>
#This is func1


2.闭包的返回值

def outer_func(a):
def inner_func(z):
print(a + z)
return inner_func

if __name__ == '__main__':
demo = outer_func(5)
demo(1)
demo(2)



3.闭包的使用场景


def funcA(func):
def funcB():
func()
print("This is funcB!")
return funcB  #返回一个函数用于被调用

@funcA
def funcD():
print("This is funcD!")

if __name__ == '__main__':
funcD()

# This is funcD!
# This is funcB!



• 8
点赞
• 15
收藏
觉得还不错? 一键收藏
• 2
评论
05-11 183
03-22 2816
06-26 445
07-30 493

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。