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__'
答案 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。我可以看到两种可能性:
out
被分配为null,因为您的solving
函数返回null。这是因为可以为out
分配solving
的返回值,例如在out = solving(v,q)
行。您必须发布solving
功能,以便我们更具体地说明这一点。
如果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
...