立即学习:https://edu.csdn.net/course/play/24797/282182?utm_source=blogtoedu
5.3 局部函数
定义说明及案例:在函数体内定义的函数称为局部函数。只在其封闭的函数内有效,其封闭函数也可以返回局部函数,以便在其它作用域中使用局部函数
def get_match_func(type,nn):
def square(n): #定义一个计算平方的局部函数①
return n*n
def cube(n): #定义一个计算立方的局部函数②
return n*n*n
def factorial(n): #定义一个计算阶乘的局部函数③
result = 1
for index in range(2,n+1):
result *= index
return result
if type == 'square':
return square(nn)
elif type == 'cube':
return cube(nn) #如改为return cube则为返回函数本身
else:
return factorial(nn)
print(get_match_func('square',3)) #>>>9
print(get_match_func('cube',3)) #>>>27
print(get_match_func('factorial',3)) #>>>6
注意:局部函数内如出现与所在函数内同名变量会导致遮蔽情况,可通过nonlocal语句解决,如:
def foo():
name = 'A' #局部变量
def bar():
nonlocal name #访问上一级即foo函数的局部变量
print(name) #>>>A
name = 'B'
bar()
foo()
foo()() #先调用foo函数再调用bar函数