是由于某种原因作为指针传递的变量?

时间:2012-04-26 09:38:18

标签: python function pointers reference module

我制作的代码有效,但我想知道原因。我不小心在代码中犯了一个错误,但由于某种原因它有效,为什么?当我将lastkeys传递给move.mov时,不应该将键作为新变量吗?与ent.playerlocation相同,player中的move.mov不应该是新变量吗?退出函数时,原始变量将更改为新变量的值。我试图重新创造这个,但是没有能力。

main.py:

import pygame
import move, updatescreen

class entities:
    def __init__(self):
        self.playerlocation = [64,64]

if __name__ == '__main__':
    pygame.init()
    screen=pygame.display.set_mode((640,360),pygame.RESIZABLE,32)#pygame.FULLSCREEN
    pygame.display.set_caption('Pygame Window')

    ent = entities()
    lastkeys = [0,0,0,0]
    ispaused = 0

    while True:
        move.userevents(lastkeys)
        move.mov(lastkeys, ent.playerlocation)
        updatescreen.gameupdate(screen,ent)

move.py:

import pygame, sys

def userevents(keys):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                keys[0] = 1
            elif event.key == pygame.K_RIGHT:
                keys[1] = 1
            elif event.key == pygame.K_UP:
                keys[2] = 1
            elif event.key == pygame.K_DOWN:
                keys[3] = 1
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                keys[0] = 0
            elif event.key == pygame.K_RIGHT:
                keys[1] = 0
            elif event.key == pygame.K_UP:
                keys[2] = 0
            elif event.key == pygame.K_DOWN:
                keys[3] = 0

def mov(keys,player):
    if keys[0]:
        player[0] -=1
    elif keys[1]:
        player[0] +=1
    if keys[2]:
        player[1] -=1
    elif keys[3]:
        player[1] +=1

2 个答案:

答案 0 :(得分:2)

当你传入一个可变对象时,它会被引用传入(因此,你对它做的任何修改都会影响原始对象)。例如:

>>> def change_list(lst):
...   lst[0] = lst[0] * 2
... 
>>> a = [1,2,3]
>>> change_list(a)
>>> a
[2, 2, 3]

因此,在将列表传递给函数之前,请先复制列表:

>>> def change_list(lst):
...   lst[0] = lst[0] * 2
... 
>>> a = [1,2,3]
>>> cpy_a = list(a)
>>> change_list(cpy_a)
>>> a
[1, 2, 3]

或者在它传递到函数之后:

>>> def change_list(lst):
...   lst_cpy = list(lst)
...   lst_cpy[0] = lst_cpy[0] * 2
... 
>>> a = [1,2,3]
>>> change_list(a)
>>> a
[1, 2, 3]

如需更全面的讨论,请参阅:How do I pass a variable by reference?

答案 1 :(得分:1)

  

当我将lastkeys传递给move.mov时,键不应该是新变量吗?

不,对象总是通过Python中的引用传递。如果将列表传递给函数,并且该函数修改了列表,那么之后可以从调用者端看到修改。