[英]"UnboundLocalError: local variable referenced before assignment" After using global variables
I'm trying to access a variable inside a function that I've already tried making global, but that doesn't work.我正在尝试访问 function 中的一个变量,我已经尝试将其设为全局变量,但这不起作用。 Here's my code (trimmed down with no unnecessary variable declarations):
这是我的代码(没有不必要的变量声明):
global col
col = 0
def interpret(text):
for char in text:
col += 1
The error I get says:我得到的错误是:
Traceback (most recent call last):
File "main.py", line 156, in <module>
interpret(line) (Where I call the function in the rest of the code)
File "main.py", line 21 (5), in interpret
col += 1
UnboundLocalError: local variable 'col' referenced before assignment
How can I fix this?我怎样才能解决这个问题?
You need to have the global
statement inside the function:您需要在 function 中包含
global
语句:
col = 0
def interpret(text):
global col
for char in text:
col += 1
Assigning col
outside the function creates the variable, but to be able to write to it inside a function, the global
statement needs to be inside each function.在 function 之外分配
col
会创建变量,但为了能够在 function 内写入它, global
语句需要在每个 function 内。
btw As a programmer you should try very, very , very hard not to use globals.顺便说一句,作为一名程序员,您应该非常、非常、非常努力地尝试不使用全局变量。
You should pass variables into functions for them to operate on:您应该将变量传递给函数,以便它们进行操作:
col = 0
def interpret(text, cnt):
for char in text:
cnt += 1
return cnt
text = ...
col = interpret(text, col) # pass col in and assign it upon return.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.