问题描述
尝试编译下面的代码时出现此错误
when trying to compile the code below I get this error
UnboundLocalError: local variable 'L' referenced before assignment
谁能解释一下为什么?不是在其他任何事情之前分配的全局变量吗?
Can someone explain why ? Isn't a global variable assigned before anything else?
我的 Python 版本是 2.7.3
My Python version is 2.7.3
#!/usr/bin/env python
import pygame
from pygame.locals import *
from sys import exit
import random
import math
R = int(8) # promien planety
N = 5 # liczba planet
G = 2 # stala "grawitacyjna"
L = 1
def compute_dv(p1,p2):
dx = p2[0]-p1[0]
dy = p2[1]-p1[1]
r = math.hypot(dx,dy)
dx /= r*r
dy /= r*r
if(L>1000):
print "r= ", r, "dx= ", dx, "dy= ", dy, "dx/ r*r = ", dx, "dy/ r*r = ", dy
L+=1
return G*dx,G*dy
def rand_color():
r = 32*random.randint(0,7)
g = 32*random.randint(0,7)
b = 22*random.randint(0,7)
return (r,g,b)
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
points = []
vs = []
colors = []
for i in range(N):
points.append( [random.randint(0,639), random.randint(0,480)] )
vs.append( [0,0] )
colors.append( rand_color() )
clock = pygame.time.Clock()
screen.fill( (255,255,255))
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
exit()
for i in range(len(points)):
for j in range(len(points)):
if points[i]!=points[j]:
dvx,dvy = compute_dv( points[i],points[j])
vs[i][0] += dvx
vs[i][1] += dvy
for i in range(len(points)):
points[i][0] += vs[i][0]
points[i][1] += vs[i][1]
screen.fill( (255,255,255))
for i in range(len(points)):
L = []
for w in points[i]:
print int(round(w))
L.append(int(round(w)))
points[i] = L
print points[i], "stop"
#x = raw_input()
pygame.draw.circle(screen, colors[i], points[i], R)
pygame.display.update()
推荐答案
重现错误的最少代码是
x = 1
def foo():
x += 1
foo()
发生这种情况的原因有很多
This is happening for a number of reasons
- 首先 - 因为在 python 中我们有可变和不可变的类.Ints 是不可变的,也就是说,当您编写
x+=1
时,您实际上创建了另一个对象(由于 CPython 的优化,某些 ints 并非如此).实际发生的是 x = x + 1. - 第二 - 因为 python 编译器会检查作用域内的每个赋值,并使该作用域内分配的每个变量都成为它的本地变量.
- 因此,当您尝试增加
x
时,编译器必须访问该范围内的本地变量,但之前从未分配过值.
- First - because in python we have mutable and immutable classes. Ints are immutable, that is when you write
x+=1
you actually create another object (which is not true for certain ints due to optimisations CPython does). What actually happens is x = x + 1. - Second - because python compiler checks every assignment made inside a scope and makes every variable assigned inside that scope local to it.
- So as you see when you try to increment
x
compiler has to access a variable that's local to that scope, but was never assigned a value before.
如果您使用的是 python2 - 您只能选择声明变量 global
.但是这样你就无法从中间函数中获取变量,比如
If you're using python2 - you only have the option to declare variable global
. But this way you would be unable to get a variable from an in-between function like
x = 0
def foo():
x = 1
def bar():
global x
print x # prints 0
bar()
foo()
在 python3 中,你有 nonlocal
关键字来解决这种情况.
In python3 you have nonlocal
keyword to address this situation.
此外,我建议您避免使用全局变量.还有一个 collection.Counter
类可能对您有用.
Also I would advise you to avoid using globals. Also there is a collection.Counter
class that might be useful to you.
进一步阅读:python 文档
这篇关于UnboundLocalError:在赋值 Python 之前引用了局部变量“L"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!