为什么方法会更改此类的属性? (蟒蛇)

时间:2020-03-02 14:28:42

标签: python object methods deque

我在下面定义了一个Snake类以及一个Move方法,该方法应该根据一个动作来计算头部的新位置,将该元素添加到blocks数组后再添加到蛇的block数组中,然后弹出该元素的第一个元素此列表。

class Snake:
    actions = [np.array([-1, 0]), np.array([1, 0]), np.array([0, -1]), np.array([0, 1])]

    def __init__(self, start_position, start_direction_idx):
        """

        :type start_position: 2x1 numpy Array
        """
        self.startPosition = None
        self.alive = True
        self.direction = start_direction_idx
        self.length = 1
        self.currentPosition = start_position
        self.blocks = deque([start_position])
        self.blockAtEndofTail = None

  def move(self, action):
        if self.isMovingBackwards(action):
            action = self.direction

        else:
            self.direction = action
        print('Blocks before anything', self.blocks)
        print('Current position before action',self.currentPosition)

        self.currentPosition += self.actions[self.direction]

        print('Current position after action', self.currentPosition)
        print('Blocks before pop',self.blocks)

        self.blockAtEndofTail = self.blocks.popleft()
        print('Blocks after pop', self.blocks)

        self.blocks.append(self.currentPosition)
        print('Blocks after append', self.blocks)

        print(self.blocks)

下面是我运行程序时获得的一些示例输出。

Blocks before anything deque([array([10, 10])])
Current position before action [10 10]
Current position after action [ 9 10]
Blocks before pop deque([array([ 9, 10])])
Blocks after pop deque([])
Blocks after append deque([array([ 9, 10])])
deque([array([ 9, 10])])

我达到了上述要求,但我希望能做到这一点:

Blocks before anything deque([array([10, 10])])
Current position before action [10 10]
Current position after action [ 9 10]
Blocks before pop deque([array([ 10, 10])])
Blocks after pop deque([])
Blocks after append deque([array([ 9, 10])])
deque([array([ 9, 10])])

我的方法如何改变双端队列的值?

1 个答案:

答案 0 :(得分:1)

在python中,对象是引用。 blocks双端队列中的值实际上是对currentPosition所引用的同一numpy数组的引用,因为它们都是从start_position初始化的。如果希望它们独立,请尝试使用copy中的内置Snake.__init__函数复制值本身而不是引用

self.blocks = deque([start_position.copy()])
相关问题