关于嵌套:
嵌套使用中, retrun inner ---> 返回的是函数的地址
retrun inner() : ---> 运行inner()函数 ---> 运行inner()函数后的返回值a(假设)返回上级 --> retrun inner()得到返回值a
如果函数没有指定返回值,那么默认的返回值就是 None
举例1:
name = "老师"
def outer():
name = "小屁孩"
def inner():
print(name)
return inner()
ret = outer()
print(ret)
#
运行结果:
举例2(易错,与举例1对比):
这里要注意的是,inner是属于 outer内部的函数,因此,“ 即使单独运行 ” inner内部的函数,其内部的参数没有定义的话,也会先去从它的上级函数找,这里inner的上级函数就是 outer
name = "老师"
def outer():
name = "小屁孩"
def inner():
print(name)
return inner
ret = outer()
ret() # 相当于运在outer当中运行了inner
print("ret = outer(): ",ret)
result = ret()
print("result = ret(): ",result) # 相当于运在outer当中运行了inner,并且要了inner的返回值
参考文献:
python基础-基础知识考试_day5 (包括:函数_递归等知识) - 努力哥 - 博客园
https://www.cnblogs.com/nulige/p/6128674.html,第30题
举例3:
这里需要注意的是,形参func存放的是外部全局定义的函数show的地址。
outer(show)()运行过程: a = outer(show) --> a()
name = "老师"
def outer(func):
print("outer!!")
def inner():
name = "李杰"
func()
return inner
def show():
print("show!!")
print(name)
outer(show)()
运行结果:
举例4(与举例3区别):
name = "老师"
def outer(func):
print("name is given when ==>>func starts",name)
def inner(name):
print("name is given when ==>>inner starts",name)
name = "李杰"
func(name)
return inner
def show(name):
print("name is given when ==>>show starts",name)
print(name)
outer(show)(name)