python函数中的变量+=1不正确地添加了2

2024-05-13 20:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个类中有一个函数move(),它在包含self.coords[1] += 1的行中错误地添加了2而不是1

以下是文件:

class Actor():
    def __init__(self, start, limits, barriers):
        self.coords = start
        self.limits = limits
        self.barriers = barriers
    
    def canmove(self, direction):
        moving = self.coords
        if(direction == 'up'):
            moving[1] -= 1
        elif(direction == 'right'):
            moving[0] += 1
        elif(direction == 'down'):
            moving[1] += 1
        elif(direction == 'left'):
            moving[0] -= 1
        
        if((moving[0] > self.limits[0]) or (moving[1] > self.limits[1]) or (-1 in moving) or (moving in self.barriers)):
            return False
        else:
            return True

    def move(self, direction):
        if(direction == 'up'):
            if self.canmove('up'):
                self.coords[1] -= 1
        elif(direction == 'right'):
            if self.canmove('right'):
                self.coords[0] += 1
        elif(direction == 'down'):
            if self.canmove('down'):
                self.coords[1] += 1
        elif(direction == 'left'):
            if self.canmove('left'):
                self.coords[0] -= 1

我知道canmove()函数还不能正常工作,但它不会影响结果

当运行Actor.move('up')时,它将Actor.coords[1]减少两个而不是一个

下面是发生的情况(即使忽略canmove()检查):

>>> from actor import Actor
>>> actor = Actor([2, 2], [10, 5], [[4, 4]])
>>> actor.move('down')  
>>> actor.coords
[2, 4]

而且actor.move(down)应该将actor.coords[1]的值增加1,而不是2


Tags: selfmoveifdefcoordsdownactorup
1条回答
网友
1楼 · 发布于 2024-05-13 20:21:34

有一个奇怪的细微差别,在canmove函数中^{}实际上并没有复制列表,它只是复制列表在内存中的位置(here is an explanation for what is going on)的引用。因此movingself.coords都指向同一个列表,这会导致canmove函数移动角色(然后当move函数移动角色时,它会移动两次)。您要做的是:

import copy
moving = copy.deepcopy(self.coords)

这将复制列表和列表中的所有项目


相关问题 更多 >