【问题标题】:Why are my different instance variables linking together despite the .copy()?尽管有 .copy(),为什么我的不同实例变量会链接在一起?
【发布时间】:2021-11-06 16:43:54
【问题描述】:

作为 python 的新手,我觉得每个小问题都问随机的陌生人问题是什么,但经过研究,我找不到问题所在。 我创建的是一个使用列表中的列表的 2D 网格移动系统。最终目标是让用户连续穿过走廊,但在第一个走廊之后,礼物会不断出现在设定的位置。但是,当用户第一次走过礼物时,礼物会从仅连接到正在编辑的列表 (currentlocation) 的硬编码艺术 (lobby_art) 中删除。 下面是从代码中挖掘问题并简化的尝试。

lobby_art = [
    ['‖ ', '  ', '  ‖'],
    ['‖ ', '????', '  ‖'],
    ['‖ ', '  ', '  ‖'],
    ['‖ ', '????', '  ‖'],
]

currentlocation = [
    ['‖ ', '  ', '  ‖'],
    ['‖ ', '  ', '  ‖'],
    ['‖ ', '  ', '  ‖'],
    ['‖ ', '????', '  ‖'],
]

def moveup(direction):
    if direction == 'w':
        global currentlocation
        global userlocationY
        if userlocationY == 0:
            global leave_corridor 
            leave_corridor = False
            currentlocation[userlocationY][1] = '  ' #deletes previous location
            return
        currentlocation[userlocationY][1] = '  ' 

        userlocationY -= 1
        currentlocation[userlocationY][1] = '????'

def lobbyprint(): #Prints Lobby layout
    global currentlocation
    for i in currentlocation: 
        print(''.join(i))

Corridor_with_present = False
GameOngoing = True  
while GameOngoing:        
    
    
    if Corridor_with_present == True:
        currentlocation = lobby_art.copy()
    
    leave_corridor = True
    userlocationY = 3
    while leave_corridor:
        lobbyprint()
        direction = input("Input w: ")
        moveup(direction)

    Corridor_with_present = True

输出

‖     ‖
‖     ‖
‖     ‖
‖ ????  ‖
Input w: w
‖     ‖
‖     ‖
‖ ????  ‖
‖     ‖
Input w: w
‖     ‖
‖ ????  ‖
‖     ‖
‖     ‖
Input w: w
‖ ????  ‖
‖     ‖
‖     ‖
‖     ‖
Input w: w
‖     ‖
‖ ????  ‖
‖     ‖
‖ ????  ‖
Input w: w
‖     ‖
‖ ????  ‖
‖ ????  ‖
‖     ‖
Input w: w
‖     ‖
‖ ????  ‖
‖     ‖
‖     ‖
Input w: w
‖ ????  ‖
‖     ‖
‖     ‖
‖     ‖
Input w: w
‖     ‖
‖     ‖
‖     ‖
‖     ‖
Input w: w
‖     ‖
‖     ‖
‖ ????  ‖
‖     ‖
Input w:

我尝试过使用.copy()、[:],甚至在语句上导入副本,但无济于事。

if Corridor_with_present == True:
        currentlocation = lobby_art.copy()

有人知道为什么吗?

谢谢罗伯特。

【问题讨论】:

标签: python instance globals


【解决方案1】:

试试这个:

import copy
if Corridor_with_present == True:
        currentlocation = copy.deepcopy(lobby_art)

lobby_art.copy() 只是复制引用,而copy.deepcopy(lobby_art) 复制整个对象到内存中。

如下图所示:

【讨论】:

    猜你喜欢
    • 2014-10-10
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多