python函数中变量LEGB原则
L-----local 局部名字空间
E-----enclosing 直接外围空间
G-----global 全局名字空间
B-----builtin 内建名字空间
变量名是按照这个顺序搜索的。
看下面这段程序:
x = 99 print("outside of function","x=",x) def funa(y): print("in the funa,x=",x) print("in the funa,y=",y) def funb(): print("in the funb,x =",x) print("in the funb,y =",y) z=x+y funb() return z print(funa(1)) print("outside of function","x=",x)
输出的结果为:
outside of function x= 99
in the funa,x= 99
in the funa,y= 1
in the funb,x = 99
in the funb,y = 1
100
outside of function x= 99