我知道这个问题不太精确,因为我也不知道发生了什么。我已将问题缩小到几行,但对我来说执行似乎相当奇怪。
def loadmaze(backup):
test = createmaze(10,10) #This creates a new 10x10 matrix
maze = placewalls(test, "x") #The X is a string with wall positions
if maze != test:
#when placewalls executed correctly, and returned a maze different from the original
showmaze(maze) #simply printing maze to console
else:
return backup #so nothing changes, looks as if function never happened
return maze,10,10
# this returns the new maze, with walls, and the dimensions of the new maze
def placewalls(amaze,positions):
#placing walls, definitely correct
return amaze-with-walls
显然我更改了变量名称,因此很清楚我在做什么。
问题是,当我调用函数 loadmaze(maze)
时,它永远不会返回带有墙壁的迷宫。不知何故,test
和 maze
值始终相同。我不明白这是怎么回事,因为有墙壁的迷宫在 test
之后被分配给 maze
,而此时它没有墙壁。
根据调试,test
也包含第三行执行后的墙壁。
请帮忙,我很困惑。
最佳答案
正如@stephan所说,变量test
和maze
引用内存中的相同对象。所以我用 maze = placewalls(createmaze(10,10),"x")
更改了 maze = placewalls(test,"x")
,从而创建了一个不同的新对象从迷宫。这会导致测试和迷宫成为两个不同的迷宫。
关于python - 为什么我的代码给出了错误的变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40948112/