获取函数内全局变量的值
Get the value of a global variable inside a function
我看到很多类似的问题,但没有和我的问题完全一样的,所以我研究了一下。
我正在尝试从我的函数 install
中的主文件访问这个变量 operatingSystem
。现在,我知道我可以用 install(operatingSystem)
传递它,但我还有 10 个类似的变量,我不想全部传递它们。
该变量在文件开头定义为 global operatingSystem
,然后在我的主函数时分配一个字符串(osx
、win
或 linux
)文件获取操作系统。
然而,当我尝试在我的 install
函数中使用 operatingSystem
时,它只是出错。我需要在我的函数中将其称为 global operatingSystem
吗?还是我必须做其他事情?
其实我没看懂你是什么人expecting.Assuming
在main.py
operatingSystem = "linux"
在yourfile.py
from main import operatingSystem
>>>operatingSystem
"linux"
不需要global
here.So
install(operatingSystem) #is possible
全局变量可以在函数中自由读取。要修改它,您需要使用 "global" 关键字。
It's all there. 如果我理解正确的话。
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print globvar # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
我看到很多类似的问题,但没有和我的问题完全一样的,所以我研究了一下。
我正在尝试从我的函数 install
中的主文件访问这个变量 operatingSystem
。现在,我知道我可以用 install(operatingSystem)
传递它,但我还有 10 个类似的变量,我不想全部传递它们。
该变量在文件开头定义为 global operatingSystem
,然后在我的主函数时分配一个字符串(osx
、win
或 linux
)文件获取操作系统。
然而,当我尝试在我的 install
函数中使用 operatingSystem
时,它只是出错。我需要在我的函数中将其称为 global operatingSystem
吗?还是我必须做其他事情?
其实我没看懂你是什么人expecting.Assuming
在main.py
operatingSystem = "linux"
在yourfile.py
from main import operatingSystem
>>>operatingSystem
"linux"
不需要global
here.So
install(operatingSystem) #is possible
全局变量可以在函数中自由读取。要修改它,您需要使用 "global" 关键字。 It's all there. 如果我理解正确的话。
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print globvar # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1