变量无意中被设定

时间:2017-11-09 21:24:39

标签: python list variables set

我正试图在屏幕上移动东西。 pygame只是为了方便文本输入。这是我的代码中的一小部分:

import pygame
pygame.init()
sensitivity = 5 # How fast it moves
rot=rot_speed = [0, 0]
done=pause = False
screen = pygame.display.set_mode((800, 450))
screen.fill((255,255,255))
pygame.display.flip()
while not done: # ---------- Main program loop ---------- #
    for event in pygame.event.get(): # If they pressed a key
        if event.type == pygame.QUIT: # Did they click quit?
            done = True
        if event.type == pygame.KEYDOWN: # Has a key been pressed?
            type_key = 1
            print("SENSITIVITY", sensitivity, rot_speed,".", rot)
            if event.key == pygame.K_w: # Up key pressed
                rot_speed[1] = sensitivity*-1
            if event.key == pygame.K_s: # Down key pressed
                rot_speed[1] = sensitivity
            if event.key == pygame.K_a: # Left key pressed
                rot_speed[0] = sensitivity*-1
            if event.key == pygame.K_d: # Right key pressed
                rot_speed[0] = sensitivity
            if event.key == pygame.K_SPACE:
                if pause == False:
                    pause = True
                else:
                    pause = False
            print("KEYS", sensitivity, rot_speed,".", rot)
    if pause == False:
        print("rot_speed", rot_speed)

我遇到的问题是,当我只尝试设置rot时,变量rot_speedrot_speed正在设置中。有任何想法吗?当我没有速度作为列表和单个变量它工作但我可能已经在其他方面改变了代码。将print语句放在变量设置周围,这很奇怪。

2 个答案:

答案 0 :(得分:2)

您为这两个名称分配了一个列表对象:

rot=rot_speed = [0, 0]

这不分配两份副本;你只需要两个不同的标签引用相同的东西。通过rot_speed也可以看到rot的任何突变:

>>> rot = rot_speed = [0, 0]
>>> rot is rot_speed   # they are the same object
True
>>> rot[0] = 42  # mutating the list
>>> rot_speed    # changes visible in both places
[42, 0]

创建两个单独的列表:

rot = [0, 0]
rot_speed = [0, 0]

您可能想要了解Python变量(名称)的工作原理。我强烈推荐Ned Batchelder的Facts and myths about Python names and values

答案 1 :(得分:1)

尝试撰写rot, rot_speed = [0, 0], [0, 0]。这会将rotrot_speed设置为单独的值。目前您拥有rot = rot_speed = [0, 0],这意味着您将rot设置为指向rot_speed的指针。因此,只有在rot_speed更改时才会更改。