python可以在局部范围内声明全局变量吗?
有用:
def main():
# do some... for files varible
for file in files:
result = func(file)
print result
我无法理解。有人告诉我为什么result
可以在for
循环之外看到。
谢谢。
for
语句不会开始新的范围。只有模块、类声明和函数定义开始一个新的作用域。
我没有看到全局变量声明。result
是一个局部变量,就像file
. 你在谈论files
吗?这看起来像一个全局变量,但我没有看到它在本地声明。
根据@DSM 的有用评论进行更新:
如果您谈论result
的是在 -loop 中本地声明for
,那么它在 Python 中不起作用,for
-loop 不会创建本地范围。
如果您的函数使用赋值=
或增强的assignemnt(即),则默认情况下+=
会考虑该变量。local
但是,如果要进行分配,请global
使用global
关键字。
foo = 2
def bar():
foo = 3 # foo is locally defined here
def car():
global foo
foo = 4 # foo is globally reassigned here
bar() # foo is still 2
car() # foo is now 4