2016-03-15 74 views
3

这是(我假设)一个基本问题,但我似乎无法弄清楚。PyGame局部变量

考虑下面的代码:

from src.Globals import * 
import pygame 
# Used to manage how fast the screen updates 
clock = pygame.time.Clock() 
# This is a list of 'sprites.' 
block_list = pygame.sprite.Group() 

def update_screen(): 
    # Loop until the user clicks the close button. 
    done = False 
    while not done: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       done = True 

     # Clear the screen 
     screen.fill(WHITE) 

     for i in blocks: 
      block_list.add(block) 

     block_list.draw(screen) 

     # Limit to 20 frames per second 
     clock.tick(20) 

     # Update the screen with what we've drawn. 
     pygame.display.flip() 

    pygame.quit() 

,一切工作正常。我可以在线程中调用函数update_screen并使其正常工作。但是,如果我移动done = False这个函数声明的,然后我得到的错误:UnboundLocalError: local variable 'done' referenced before assignment.

我的问题是:为什么是我可以放心地有clock,并且block_list以外的功能,但不done

+1

您需要在函数的顶部声明'全球done'因此荣获:

您可以通过以下网址获取更多不是一个局部变量。您不需要使用'clock'和'block_list'来完成这个工作,因为您不需要为它们赋值并仅引用它们的当前值。 – martineau

+1

我发现使用全球实际上使其全球化将有所帮助。你的解释有助于说清楚为什么:因为我没有改变其他的价值观。 – Teknophilia

+0

Python遵循所谓的[LEGB规则](http://stackoverflow.com/a/292502/355230)来查找变量(并在分配时确定它们是否是本地的)。 – martineau

回答

3

均线之上函数来完成变量之后,你必须明确地指向解释器函数中done变量是全球

done = False 
def update_screen(): 
    # Loop until the user clicks the close button. 
    global done 
    while not done: 
    # ....... 

你的情况下,与global识别变量,如果你有直接分配到变量,例如a = 10。在上面的代码片段中,一切工作正常,对于clockblock_list,因为在函数体内没有直接赋值给该变量。

这是必需的,因为所有变量,在函数体中分配的值都被视为函数局部变量。