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

时间:2015-09-21 00:40:28

标签: python types

def solve(v,q):
  #print "reach solve"
  if isInside(v,left(q)) == True:
    out = solving(v,q)
  elif isInside(v, right(q)) == True:
    reverse = q[::-1]
    #reverse = [right(q) + '=' + left(q)]
    out = solving(v,reverse)
  #if type(out[0]) == types.ListType:
  print out[0]
  if out[0] == "x":
    pass
  else:
    out = solving(v,out)
  return out

尝试运行程序时收到以下消息。 out [0]应该是一个“x”字符串。我有几个成功的测试用例,但其中有几个在这一点上失败了。

任何人都可以向我解释这里可能发生的事情。谢谢!

Traceback (most recent call last):
  File "lab1.py", line 147, in <module>
    main()
  File "lab1.py", line 131, in main
    print solve('x', [['a', '-', 'x'], '=', 'c'])  #  ['x', '=', ['a', '-', 'c']]
  File "lab1.py", line 109, in solve
    print out[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

1 个答案:

答案 0 :(得分:0)

错误

TypeError: 'NoneType' object has no attribute '__getitem__'

表示您尝试以非法方式使用null(&#39; NoneType&#39;)引用。 Here's another example

print out[0]引用out的第一个元素,因此out需要是可迭代的,即具有列表等有序元素。由于null不可迭代,因此运行时不知道如何获取其第一个元素,而是抛出该错误。

您需要弄清楚如何将out指定为null。我可以看到两种可能性:

  1. out被分配为null,因为您的solving函数返回null。这是因为可以为out分配solving的返回值,例如在out = solving(v,q)行。您必须发布solving功能,以便我们更具体地说明这一点。

  2. 如果out 不是本地变量,即您已在代码中的其他位置初始化它,则它可能已初始化为null且从未重新分配。正如其他答案所指出的,您的if / elif结构并不能保证在该函数中分配out。这种情况看起来像:

  3. out = null # out is set to null
    
    def solve(v,q):
      if isInside(v,left(q)) == True: # say isInside(v,left(q)) is False
        out = solving(v,q)
      elif isInside(v, right(q)) == True: # say isInside(v, right(q)) is False
        reverse = q[::-1]
        out = solving(v,reverse)
      # both the if and elif were false, so out was never reassigned 
      # this means out is still null
      print out[0] # error
      ...