Python中定义函数时,若想在函数内部对函数外的变量进行操作,就需要在函数内部声明其为global。
例子1
x = 1
def func():
x = 2
func()
print(x)
结果为1
因为并没申明global,内部函数并不能对外部变量进行改变
例子2
x = 1
def func():
global x = 2
func()
print(x)
结果为2
因为申明了global,内部函数对外部变量进行了改变
例子3
global x = 1
def func():
x = 2
func()
print(x)
结果为1
global 只能在内部申明,外部申明依然不能达到效果
作者:xtingjie
来源:优快云
原文:https://blog.youkuaiyun.com/xtingjie/article/details/71210182