TypeError:'NoneType'对象没有属性'__getitem__'

use*_*896 23 python typeerror

我遇到了问题,我不知道为什么会这样,以及如何解决它.我正在使用python和pygame开发一个Videogame,我收到了这个错误:

 File "/home/matt/Smoking-Games/sg-project00/project00/GameModel.py", line 15, in Update 
   self.imageDef=self.values[2]
TypeError: 'NoneType' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)

代码:

import pygame,components
from pygame.locals import *

class Player(components.Entity):

    def __init__(self,images):
        components.Entity.__init__(self,images)
        self.values=[]

    def Update(self,events,background):
        move=components.MoveFunctions()
        self.values=move.CompleteMove(events)
        self.imageDef=self.values[2]
        self.isMoving=self.values[3]

    def Animation(self,time):
        if(self.isMoving and time==1):
            self.pos+=1
            if (self.pos>(len(self.anim[self.imageDef])-1)):
                self.pos=0
        self.image=self.anim[self.imageDef][self.pos]
Run Code Online (Sandbox Code Playgroud)

你能解释一下这个错误意味着什么以及为什么会这样,我能解决它吗?

小智 24

BrenBarn是对的.错误意味着你试图做类似的事情None[5].在回溯中,它说self.imageDef=self.values[2],这意味着你self.valuesNone.

您应该检查所有更新的功能,self.values并确保您考虑所有角落情况.

  • 感谢大家帮助我,我可以解决问题,返回语句中有一个缩进错误,所以它返回无lol (4认同)

Bur*_*lid 6

move.CompleteMove()不返回值(也许它只是打印一些东西).任何不返回值的方法都会返回None,并且已分配Noneself.values.

这是一个例子:

>>> def hello(x):
...    print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>
Run Code Online (Sandbox Code Playgroud)

您将注意到y不打印任何内容,因为它None(在交互式提示符下不打印任何内容的唯一值).