【发布时间】:2020-12-12 10:04:09
【问题描述】:
我是 Python 新手。我无法弄清楚为什么全局变量似乎被执行递归代码破坏了。
globVar = []
def explore(X, Y):
global globVar
globVar = X
print()
print("set: "+str(X)) # This is the only place where the global variable is set
for i in range(1, 5):
X[Y] = i
if Y < 2:
print(" =? " + str(globVar) + " <<< Here has the next global value. Why? Global Var should't do that!")
explore(X, Y + 1)
print(" =? " + str(globVar) + " OK here")
# Launch recursive exploration
explore([1,1,1],0)
这是前面代码返回的摘录:
...
set: [1, 2, 4]
=? [1, 2, 4] OK here
=? [1, 3, 4] <<< Here has the next global value. Why? Global Var should't do that!
set: [1, 3, 4]
...
知道为什么 globVar 似乎会受到递归上下文的影响吗?
我本来希望它的值只是最后一个值集。 但这不是打印输出显示的内容。
谢谢你们!
【问题讨论】:
标签: python variables recursion scope global