根据我的理解,Python 有一个单独的函数命名空间,所以如果我想在函数中使用全局变量,我可能应该使用global
.
但是,即使没有,我也能够访问全局变量global
:
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
为什么这有效?
See also UnboundLocalError on local variable when reassigned after first use https://stackoverflow.com/questions/370357 for the error that occurs when attempting to assign to the global variable without global
. See Using global variables in a function https://stackoverflow.com/questions/423379/ for the general question of how to use globals.
关键词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
在本地上下文中声明函数、类或其他对象。尽管我建议不要这样做,因为如果出现问题或需要调试,它会导致噩梦。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)