作者:mobiledu2502929547 | 来源:互联网 | 2023-09-05 17:58
我正在尝试使用Python设置弹丸运动路径的动画.为此,我使用了matplotlib的动画模块.我的完整脚本如下.#!usrbinenvpythonimportmathimport
我正在尝试使用Python设置弹丸运动路径的动画.为此,我使用了matplotlib的动画模块.我的完整脚本如下.
#!/usr/bin/env python
import math
import sys
import matplotlib.animation as anim
from matplotlib.pyplot import figure, show
# Gravitational acceleration in m/s/s
g = -9.81
# Starting velocity in m/s.
vel = 100
# Starting angle in radians.
ang = 45 * math.pi / 180
# Starting height in m.
y0 = 0
# Time settings.
t = 0
dt = 0.1
time = -vel**2 * math.sin(2 * ang) / g
def projectile():
print g, vel, ang, y0, dt, time
print t # Crashes here with UnboundLocalError: local variable 't' referenced before assignment
t=0 # With this it works
x = 0
y = 0.1
xc = []
yc = []
# Simulate the projectile.
while t x = vel * math.cos(ang) * t
y = vel * math.sin(ang) * t + (g * t**2) / 2 + y0
if y <0:
break
t += dt
xc.append(x)
yc.append(y)
yield x, y
def update_frame(sim):
x, y = sim[0], sim[1]
line.set_data(x, y)
return line,
def init():
line.set_data([], [])
return line,
# Show the results.
fig = figure()
ax = fig.add_subplot(111)
ax.set_xlim([-5,1500])
ax.set_ylim([0,300])
# ax.plot returns a single-element tuple, hence the comma after line.
line, = ax.plot([], [], 'ro', ms=5)
ani = anim.FuncAnimation(fig=fig, func=update_frame, frames=projectile, blit=True, interval=20, init_func=init, repeat=False)
show()
我的问题是我似乎能够使用除t之外的所有变量.我这样做是为了创建一个停止条件,因此它只能运行一次,后来我发现了repeat = False,但是我对此仍然感到好奇.为什么不能在弹丸内使用t?我正在用Anaconda 1.9.1软件包中的Matplotlib 1.3.1运行Python 2.7.6.
解决方法:
出现问题是因为您尝试重新分配全局变量t.
变量g,vel,ang,y0,dt只能访问(不重新分配它们)的时间,因此python尝试在本地然后全局访问它们.但是,当您用t = dt行重新分配t时,您实际上是在告诉python创建一个带有标识符t的局部变量,并为其分配所需的值.因此,无法像您告诉python t是本地的那样访问全局标识符t,并且当您尝试在分配t之前访问t时,将引发UnboundLocalError.
要告诉python将t重新分配为全局变量,您只需要将global t添加到函数的开头:
t = 0
(..)
def projectile():
print g, vel, ang, y0, dt, time
global t # now t can be edited as a global variable
print t #works
x = 0
y = 0.1
xc = []
yc = []
while t (..)
t += dt
编辑:
正如flebool所指出的,只要不重新为其分配标识符,实际上您仍然可以更改全局变量.例如,下面的代码是有效的:
>>> l = [1,2,3]
>>> def changelist():
... l.append(4)
...
>>> changelist()
>>> l
[1,2,3,4]