全局变量的未绑定本地错误


问题内容

我试图弄清楚为什么我的pygame应用程序Table Wars中出现UnboundLocalError。以下是发生的情况的摘要:

变量,REDGOLDREDCOMMANDBLUEGOLDBLUECOMMAND,被初始化为全局变量:

#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100

def main():

    [...]

    global REDGOLD
    global REDCOMMAND
    global BLUEGOLD
    global BLUECOMMAND

当在主循环中生成单位时,这会起作用,但会在生成单位中减去资金。

现在,我正在尝试建立一个系统,以便当一个单位死亡时,杀手根据受害者的被害人退款给受害者COMMAND并赚取收益GOLD

class Red_Infantry(pygame.sprite.Sprite):
def __init__(self, screen):
    [...]
    self.reward = 15
    self.cmdback = 5

[...]

def attack(self):
    if self.target is None: return
    if self.target.health <= 0:
        REDGOLD += self.target.reward          #These are the problem lines
        BLUECOMMAND += self.target.cmdback     #They will cause the UnboundLocalError
                                               #when performed
        self.target = None
    if not self.cooldown_ready(): return
    self.target.health -= self.attack_damage
    print "Target's health: %d" % self.target.health

这可以一直工作到单元死亡。然后发生这种情况:

Traceback (most recent call last):
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 606, in <module>
main()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 123, in main
RedTeam.update()
File "C:\Python27\lib\site-packages\pygame\sprite.py", line 399, in update
for s in self.sprites(): s.update(*args)
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 304, in update
self.attack()
File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 320, in attack
REDGOLD += self.target.reward
UnboundLocalError: local variable 'REDGOLD' referenced before assignment

我如何使上述全局变量随attack块一起变化?如果有帮助,我正在使用Pygame 2.7.x,因此nonlocal将无法工作:/


问题答案:

global使全局变量在当前代码块中可见。您只能将global语句放入main,而不能放入attack

附录

这说明了多次使用全局的必要性。尝试这个:

RED=1

def main():
    global RED
    RED += 1
    print RED
    f()

def f():
    #global RED
    RED += 1
    print RED

main()

您将得到错误UnboundLocalError: local variable 'RED' referenced before assignment

现在取消注释f中的全局语句,它将起作用。

global声明在LEXICAL而不是DYNAMIC范围内处于活动状态。