【问题标题】:'NoneType' object is not iterable“NoneType”对象不可迭代
【发布时间】:2016-02-08 12:20:51
【问题描述】:

我正在尝试迭代一个元组数组(以常量的形式):

SPRITE_RIGHT = [(0, 0), (16, 0), (32, 0)]
SPRITE_LEFT = [(0, 16), (16, 16), (32, 0)]
SPRITE_UP = [(0, 32), (16, 32), (32, 0)]
SPRITE_DOWN = [(0, 48), (16, 48), (32, 0)]
def symbol(self):
    self._status += 1

    if (self._status > 2):
        self._status = 0

    if (self._dx > 0):
        (x, y) = PacMan.SPRITE_RIGHT[self._status]
        return (x,y)
    if (self._dx < 0):
        (x, y) = PacMan.SPRITE_LEFT[self._status]
        return (x,y)
    if (self._dy > 0):
        (x, y) = PacMan.SPRITE_DOWN[self._status]
        return (x,y)
    if (self._dy < 0):
        (x, y) = PacMan.SPRITE_UP[self._status]
        return (x,y)
...
for a in arena.actors():
        if not isinstance(a, Wall):
            x, y, w, h = a.rect()
            xs, ys = a.symbol()                #This line gives me the problem
            screen.blit(sprites, (x, y), area=(xs, ys, w, h))

当我执行程序时收到此错误:

TypeError: 'NoneType' object is not iterable

对于每个演员,我调用方法 symbol() 来获取其图像

例如,当我打印 PacMan.SPRITE_UP[0] 时,它会返回正确的 元组

【问题讨论】:

  • 假设self._status 的值合理,您发布的代码似乎是正确的。也许你省略了太多。您能否尝试制作一个在执行时仍显示错误的最小工作示例?
  • 所以 SPRITE_RIGHT[self._status] 是 None
  • 这是重现错误的最小示例

标签: python typeerror nonetype


【解决方案1】:

检查a.symbol() 返回的值。看起来它正试图将其分解为两个值并且失败了。

当你这样做时:

xs, ys = a.symbol()     #This line gives me the problem

它调用a.symbol(),它返回一个值。该代码假定这 value 是一个包含两个值的可迭代对象。然后xsys 更改为对这两个值的引用。

如果a.symbol() 返回的值不是这样的 可迭代,分配将失败。你得到的错误信息, TypeError: 'NoneType' object is not iterable,建议 a.symbol() 正在返回 None

【讨论】:

  • 当我打印 PacMan.SPRITE_UP[0] 例如它返回正确的元组
  • 谢谢,我解决了这个问题。我没有考虑 dx 的特定值
猜你喜欢
  • 2020-05-06
  • 1970-01-01
  • 2013-12-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多