简体   繁体   中英

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

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

I receive the following message when I try to run the program. out[0] should be a string of "x". I have several successful test case, but several of them fail at this point.

Could any one please explain to me what potentially happen here. Thank you!

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 is defined in your if statements and may never get assigned if the condition is not True. Before the first if statement, add out[0] = None .

The error

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

means that you are trying to use a null ('NoneType') reference in an illegal way. Here's another example .

The line print out[0] references the first element of out , so out needs to be an iterable, ie have ordered elements like a list. Since null isn't iterable, the runtime doesn't know how to get its first element and instead throws that error.

You need to figure out how out is getting assigned to null. There are two possibilities that I can see:

  1. out is getting assigned to null because your solving function is returning null. This is because out may be assigned the return value of solving , eg on the line out = solving(v,q) . You'd have to post the solving function for us to say anything more specific about this.

  2. If out is not a local variable , ie you have initialized it elsewhere in the code, then it could have been initialized to null and never reassigned. As other answers have pointed out, your if/elif structure doesn't guarantee that out gets assigned in that function. This scenario would look something like:

.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM