What's causing this variable referenced before assignment error?

后端 未结 3 937
深忆病人
深忆病人 2021-01-21 18:58

This is the code that I am working with:

import pygame

global lead_x
global lead_y
global lead_x_change
global lead_y_change

lead_x = 300
lead_y = 300
lead_x_c         


        
相关标签:
3条回答
  • 2021-01-21 19:14

    Python doesn't need global variables declared in any special way. Just declare and initialize your variables at the top like you did in the second chunk of code. Then move your global declarations to inside each method that CHANGES your global. So you can cut your first chunk and paste into your method.

    Note that to READ a global you don't need to use the global keyword. This can help keep your constants constant, since Python doesn't handle constants specially.

    0 讨论(0)
  • 2021-01-21 19:23

    If you need to modify a global variable from inside a function you need to use the global keyword: global lead_x in this case, before any assignment

    0 讨论(0)
  • 2021-01-21 19:41

    Python's handling of "global" variables is indeed a bit weird, especially if you're not accustomed to it.

    The simple fix for your problem is to move your global declarations inside each function that uses those variables. So:

    def playerUpdateMovement():
        global lead_x
        global lead_y
        global lead_x_change
        global lead_y_change
    
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            lead_x_change = -1
    

    This tells Python that your use of lead_x_change within the playerUpdateMovement function is actually a reference to a global variable, and not a use of a local variable (of the same name), which is the default treatment.

    0 讨论(0)
提交回复
热议问题