Python:赋值之前引用的局部变量

2024-09-30 01:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我总是犯错误

UnboundLocalError: local variable 'new_speedDx' referenced before assignment

尝试运行以下函数时:

def new_speedD(boid1):
    bposx = boid1[0]
    if bposx < WALL:
        new_speedDx = WALL_FORCE
    elif bposx > WIDTH - WALL:
        new_speedDx = -WALL_FORCE

    bposy = boid1[1]
    if bposy < WALL:
        new_speedDy = WALL_FORCE
    elif bposx > WIDTH - WALL:
        new_speedDy = -WALL_FORCE

    return new_speedDx, new_speedDy

在这个函数中,boid1是一个包含4个元素(xpos,ypos,xvelocity,yvelocity)的向量,所有大写的变量都是常量(数字)。 有人知道怎么解决这个问题吗?我在网上找到了许多可能的解决办法,但似乎没有任何办法。。在


Tags: 函数newiflocalwidthforceelifwall
3条回答

必须有可能,bposx既不小于墙,也不大于墙宽。在

例如:

bposx = 10
WALL = 9
WIDTH = 200

if bposx < WALL:    # 10 is greater than 9, does not define new_speedDx 
    new_speedDx = WALL_FORCE
elif bposx > WIDTH - WALL:   # 10 is less than (200 - 9), does not define new_speedDx
    new_speedDx = -WALL_FORCE

如果不查看程序的其他部分,很难建议合理的回退值,但您可能希望添加以下内容:

^{pr2}$

解释

正如其他人所指出的,您所处理的不是WALL <= pos <= WIDTH - WALL。在

建议变更

如果boid没有撞到墙,它可能会继续以当前的速度前进。其他的程序可以在boid没有撞到墙的情况下将速度设置为0。这个解决方案在使用现有速度方面是与众不同的。我认为这对你的处境很重要。在

代码

def new_speedD(boid1):
    def new_speed(pos, velocity):
        return WALL_FORCE if pos < WALL \
            else (-WALL_FORCE if pos > WIDTH - WALL \
            else velocity)
    xpos, ypos, xvelocity, yvelocity = boid1
    new_speedDx = new_speed(posx, xvelocity)
    new_speedDy = new_speed(posy, yvelocity)
    return new_speedDx, new_speedDy

有些人认为这个代码很难理解。以下是简要说明:

  1. 如果位置为墙,则返回墙力(<;墙
  2. 否则,如果位置为>;宽度-墙,则返回-墙力
  3. 否则,返回速度

这是一个general question on the ternary operator。记得吗,心想,“这是一些Python不喜欢的。”

如果你不使用这个代码

返回原稿并修复yvelocity大小写中的错误:bposx > WIDTH - WALLyvelocity不依赖于xpos。在

如果这两个条件都不成立,会发生什么?在

if bposx < WALL:
    new_speedDx = WALL_FORCE
elif bposx > WIDTH - WALL:
    new_speedDx = -WALL_FORCE

。。。new_speedDx从未赋值,因此其值不确定。在

在这种情况下,可以通过指定new_speedDx应该是什么来缓解这种情况:

^{pr2}$

相关问题 更多 >

    热门问题