【问题标题】:Python_TypeError: 'NoneType' object has no attribute '__getitem__'Python_TypeError:“NoneType”对象没有属性“__getitem__”
【发布时间】:2015-12-17 14:19:02
【问题描述】:
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__'

【问题讨论】:

  • 您的“解决”方法似乎返回无。所以,你的 out 变量是 None 而不是一个列表。
  • 请发布整个代码。或者你可以尝试自己调试,使用 eclipse 或 pycharm

标签: python types


【解决方案1】:

错误

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

表示您正试图以非法方式使用 null ('NoneType') 引用。 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 。这个场景看起来像:

.

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
  ...

【讨论】:

    【解决方案2】:

    out 在您的if 语句中定义,如果条件不为真,则可能永远不会被分配。在第一个if 语句之前,添加out[0] = None

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 2018-04-13
      • 2013-04-15
      相关资源
      最近更新 更多