据我了解,Python 有一个单独的函数命名空间,所以如果我想在函数中使用全局变量,我可能应该使用 global
。
但是,即使没有 global
,我也能够访问全局变量:
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
为什么会这样?
另见UnboundLocalError on local variable when reassigned after first use尝试在没有 global
的情况下分配给全局变量时发生的错误。见 Using global variables in a function关于如何使用全局变量的一般问题。
最佳答案
关键字 global
仅对在本地上下文中更改或创建全局变量有用,尽管创建全局变量很少被认为是一个好的解决方案。
def bob():
me = "locally defined" # Defined only in local context
print(me)
bob()
print(me) # Asking for a global variable
以上将为您提供:
locally defined
Traceback (most recent call last):
File "file.py", line 9, in <module>
print(me)
NameError: name 'me' is not defined
如果您使用 global
语句,则该变量将在函数范围“外部”可用,从而有效地成为全局变量。
def bob():
global me
me = "locally defined" # Defined locally but declared as global
print(me)
bob()
print(me) # Asking for a global variable
所以上面的代码会给你:
locally defined
locally defined
此外,由于 python 的特性,您还可以使用 global
在本地上下文中声明函数、类或其他对象。虽然我建议不要这样做,因为如果出现问题或需要调试,它会导致噩梦。
关于python - 为什么访问全局变量不需要 'global' 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4693120/