函数的嵌套
函数的嵌套
def func()
print(1)
def f1():
print(2)
return f1()
func()
结果为:1 2
不管在什么位置,只要是函数+()就是在调用此函数
函数调用执行后,函数体中开辟的空间就自动销毁了
def func():
a=1
def foo():
b=2
print(b)
print(a)
def f1():
print(b)
return f1()
return foo()
print(func())
结果为:2 1 2 None
print(func()) 输出func()的返回值
如果 函数里没有此变量 就找上面那一层(即父子层)
函数的相互引用
def func():
a=1
foo():
print(a)
def foo():
b=2
print(b)
func()
结果为:2 1
def a():
a1=1
c()
print(c)
def b():
b1=2
print(b1)
def c():
c1=3
print(a)
def run():
a()
print(run())
结果为:
<function a at 0x0000024CE8801E18>
<function c at 0x0000024CE89DA950>
None
def func():
a=1
def b():
print(a)
def foo():
b=1
def z():
print(func)
print(b)
ret=z()
func()
return ret
def run()
foo()
print(run())
结果为:
<function func at 0x00000242CF281E18>
1
None
def func(a):
foo(a)
def foo(e):
b(e)
def b(c):
print(c)
return 10
print(func(5))
结果为:
5
None
4.5 global 及 nonlocal
global(声明修改全局变量的值)
a=10
def func():
global a # 声明修改全局变量的值
a += 1
print(a)
func()
print(a)
结果为: 11 11
a = 10
def f1():
a = 10
def f2():
a = 15
def f3():
global a
a += 1
print(a) # 11
print(a) # 15
f3()
print(a) # 10
f2()
f1()
结果为:10 15 11
a=10
def func():
def f1():
a=15
def foo():
nonlocal a
a+=1
print(a)
foo()
print(a)
f1()
func()
print(a)
结果为:16 16 10
总结: