我将全局变量'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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句