[英]Why aren't my globals global?
I have the following lines at the beginning of my script: 我的脚本开头有以下几行:
global lotRow
global lotCol
Then, later on, I set lotRow and lotCol as strings using a function. 然后,稍后,我使用函数将lotRow和lotCol设置为字符串。 Then, even later, I do the following: 然后,甚至以后,我执行以下操作:
getIDFromAxes(int(lotRow), int(lotCol))
This gives me: 这给了我:
getIDFromAxes(str(lotRow), str(lotCol))
NameError: global name 'lotRow' is not defined
I have the def() print the "lot" strings at the end to be sure they are set, and I still can't access them for some reason. 我让def()在最后打印“很多”字符串以确保已设置它们,但由于某些原因我仍然无法访问它们。
global
statements don't go at the beginning of a script; global
语句不在脚本的开头。 they go inside of a function that needs access to global variables. 它们位于需要访问全局变量的函数内部。 So rather than: 因此,而不是:
global x
x = 0
def increment_x():
x += 1
return x
You'll need to use: 您需要使用:
x = 0
def increment_x():
global x
x += 1
return x
You'll need to use the keyword global
when inside the function that is trying to access your global variables, otherwise it will look for a local definition - which of course doesn't exist. 在试图访问全局变量的函数内部时,您将需要使用关键字global
,否则它将寻找局部定义-当然不存在。
global global_variable
def set_var ():
global global_variable
global_variable = 3
def print_var ():
global global_variable
print int(global_variable)
set_var ()
print_var ()
global_variable = 321
print_var ()
output: 输出:
3
321
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.