python - 为什么我的代码给出了错误的变量值?

标签 python python-3.x variables

我知道这个问题不太精确,因为我也不知道发生了什么。我已将问题缩小到几行,但对我来说执行似乎相当奇怪。

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) 时,它永远不会返回带有墙壁的迷宫。不知何故,testmaze 值始终相同。我不明白这是怎么回事,因为有墙壁的迷宫在 test 之后被分配给 maze,而此时它没有墙壁。 根据调试,test包含第三行执行后的墙壁。 请帮忙,我很困惑。

最佳答案

正如@stephan所说,变量testmaze引用内存中的相同对象。所以我用 maze = placewalls(createmaze(10,10),"x") 更改了 maze = placewalls(test,"x") ,从而创建了一个不同的新对象从迷宫。这会导致测试和迷宫成为两个不同的迷宫。

关于python - 为什么我的代码给出了错误的变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40948112/

相关文章:

python - Google Wave Python 教程 - 下一步是什么?

python - 在 python 中使用 Sin-1 或反 sin

python - 删除字典中列表中的所有值

python-3.x - 当输出标签是3D数组时如何使用SVM?

variables - 将 Homebrew 程序添加到 PATH

python - 如何在traitsui生成的窗口中分配HSplit

python - 使用带有 zmq 和 python 的套接字通过 send_json 发送整数列表时出现奇怪的错误

python - Google 图片 APIexecute_transforms() 返回 "there has been an error"

python import-ed变量保持相同的值,尽管它正在改变

c++ - 方法中的静态局部变量是一种不好的做法?