English 中文(简体)
带有全局变量的无约束本地错误 [重复]
原标题:Unbound Local Error with global variable [duplicate]

我试图弄清楚为什么在我的游戏应用程序“桌战”中 会有一个无线本地错误。这里是所发生事情的概要:

变量 REDGOLD REDCOMMAND BLUEGOLD BLUECOMMAND 被作为全球变量初始化:

#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:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 606, in <module>
main()
File "C:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 123, in main
RedTeam.update()
File "C:Python27libsite-packagespygamesprite.py", line 399, in update
for s in self.sprites(): s.update(*args)
File "C:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 304, in update
self.attack()
File "C:UsersOventoasterDesktopGamesTable WarsTable Wars.py", line 320, in attack
REDGOLD += self.target.reward
UnboundLocalError: local variable  REDGOLD  referenced before assignment

如何用 < code> attack 块改变上述全球变量? 如果有用, 我使用 Pygame 2.7. x, 所以 < code > 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()

您将会得到错误 < code> UnmundlocalError: 任务 之前引用的本地变量 RED 。

现在在f中不提全球声明,它将发挥作用。

global 声明在Lexical范围内很活跃,不是DYNAMIC范围。

问题回答

您需要将变量声明为正在修改的每个范围内的全局变量

最好还是想个办法不使用全局。 将这些属性作为类属性是否合理?

发现在函数中 main 中的变量与全局“只读”变量相似。如果我们试图重新指定值,它将产生错误。

尝试 :

#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]

def f():
    print A[RED]

f()

没关系 It ok.

但是:

#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]

def f():
    print A[RED]
    A = [1,1,1,1,1]

f()

生成生成

  File "./test.py", line 6, in f
    print A[RED]
UnboundLocalError: local variable ** A ** referenced before assignment

并且:

#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]

def f():
    print A[RED]
    RED = 2

f()

生成生成

  File "./test.py", line 6, in f
    print A[RED]
UnboundLocalError: local variable ** RED ** referenced before assignment




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签