|
发表于 2022-4-11 15:24:25
|
显示全部楼层
>>> def myfunc():
x=520
print(x)
>>> myfunc()
520
>>> print(x)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print(x)
NameError: name 'x' is not defined
>>> x=880
>>> def myfunc()
SyntaxError: invalid syntax
>>> def myfunc():
print(x)
>>> myfunc()
880
>>> def myfunc():
x=520
print(x)
>>> myfunc()
520
>>> print(x)
880
>>> x=880
>>> id(x)
2567052254064
>>> def myfunc():
x=520
print(id(x))
>>> myfunc()
2567052938160
>>> id(x)
2567052254064
>>> x=880
>>> def myfunc():
global x
x=520
print(x)
>>> myfunc()
520
>>> print(x)
520
>>> def funA():
x=520
def funB():
x=880
print("In funB,x=",x)
>>> def funA():
x=520
def funB():
x=880
print("In funB,x=",x)
print("In funA,x=",x)
>>> funB()
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
funB()
NameError: name 'funB' is not defined
>>> #内部函数无法直接调用
>>> def funA():
x=520
def funB():
x=880
print("In funB,x=",x)
funB()
print("In funA,x=",x)
>>> funA()
In funB,x= 880
In funA,x= 520
>>> #内部函数可以访问外部函数的变量,但不是改变其赋值
>>> def funA():
x=520
def funB():
nonlocal x
x=880
print("In funB,x=",x)
funB()
print("In funA,x=",x)
>>> funA()
In funB,x= 880
In funA,x= 880
>>> #LEGB L 是local 局部作用域(含嵌套函数的内层作用域),E Enclosed嵌套函数的外层的作用域 |
|