Python 混合全局变量和局部变量?
Python mixing global and local variable?
我将一个全局变量'i'初始化为0和一个函数定义。
在 def 中,我想将本地 'j' 初始化为全局 'i',然后将 1 分配给全局 'i',但是编译器认为当我将 1 分配给 'i' 时,我初始化它。
这不起作用:
i = 0
def doSomething():
j = i # compiler throws UnboundLocalError here
i = 1
这是有效的:
i = 0
def doSomething():
j = i
修改前需要在函数内声明全局变量。
i = 0
def doSomething():
global i #needed to modify the global variable.
j = i # compiler throws UnboundLocalError here
i = 1
我将一个全局变量'i'初始化为0和一个函数定义。 在 def 中,我想将本地 'j' 初始化为全局 'i',然后将 1 分配给全局 'i',但是编译器认为当我将 1 分配给 'i' 时,我初始化它。
这不起作用:
i = 0
def doSomething():
j = i # compiler throws UnboundLocalError here
i = 1
这是有效的:
i = 0
def doSomething():
j = i
修改前需要在函数内声明全局变量。
i = 0
def doSomething():
global i #needed to modify the global variable.
j = i # compiler throws UnboundLocalError here
i = 1