簡體   English   中英

在函數之外在Python中聲明全局變量

[英]Declaring Global Variables in Python Outside of Functions

原諒我是否曾經被問過,但是我無法弄清楚為什么這不起作用。 為了記錄,我已經在Google上搜索了幾個小時。 我不斷收到全局變量錯誤。 我這樣聲明我的全局變量:

###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] blit到表面上),

如果您知道其他方法,請告訴我。 我以前用JASS編碼(這就是為什么我有一種聲明全局變量的時髦方式)的原因,而且我不知道該如何保持列表在所有函數中都可以訪問。

非常感謝! -扎克

為了使用全局,實際上需要在方法中顯式設置它。 這是一個可以幫助您的示例:

glb = "I am global"

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

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

除了全局關鍵字之外,您的變量名也需要匹配。 您定義global_AB ,然后僅引用AB

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM