【问题标题】:Declaring Global Variables in Python Outside of Functions在函数之外的 Python 中声明全局变量
【发布时间】:2015-10-06 01:28:44
【问题描述】:

如果以前有人问过这个问题,请原谅我,但我无法弄清楚为什么这不起作用。为了记录,我已经用谷歌搜索了几个小时。 我不断收到全局变量错误。我这样声明我的全局变量:

###Sprites###
global_AB = []
global_AM = []
global_AD = []
global_BB = []
global_CO = []
global_DK = []
global_FB = []
global_O = []
global_R = []
global_SS = []
global_S = []
global_WU = []

但是当我在一个函数中访问它时(在它被这个函数设置之后)

#Loads all of the sprites and backgrounds, I recommend you close this if looking at the code.
def loadImages():
    for i in range(0, (len(spriteNames) - 1)):
        for z in range(0, numSprites[i]):
            if i == 0:
                AB.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
            elif i == 1:
                AM.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
            elif i == 2:
                AD.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
           ... 8 more of these

当被 blit 图像访问时,我收到一个错误,说它没有定义(我试图将 AB[0] 复制到表面上),

如果您知道另一种方法,请告诉我。我以前在 JASS 中编码(这就是为什么我有一种声明全局变量的时髦方式),但我不知道如何保持列表能够在所有函数中访问。

非常感谢! - 扎克

【问题讨论】:

  • 如果是声明全局变量,需要使用global关键字:global foo = []
  • 另外,与一堆类似名称的列表相比,使用字典会更好sprites = {"AB": [], "AM": [], ... }

标签: python pygame global-variables global declare


【解决方案1】:

为了使用全局变量,您需要在方法中实际显式设置它。这是一个可以帮助您的示例:

glb = "I am global"

def foo():
    global glb
    glb = "I changed you mr. global"

foo()
# Outputs:  I changed you mr. global
print(glb) 

【讨论】:

    【解决方案2】:

    除了 global 关键字,你的变量名需要匹配。您定义global_AB,然后仅引用AB

    【讨论】:

      猜你喜欢
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多