Search code examples
pythontypesabsolute-value

type error in python


I have a list of ints (hitTableWord) and I am trying to add 1 over the absolute value of the numbers for the whole list and I keep getting this error message in python: metric = metric + 1/(abs(metricNumber)) TypeError: unsupported operand type(s) for +: 'type' and 'float'. metric was initialized as: metric = 0

Thing is I am a rookie programmer and don't know what it means.

 for a in range (0, len(hitTableWord)):
         output_file.write('Hit Word: '+ str(hitTableWord[a]) +' ' + str(hitTableNear[a])+ ', ')
         metric = metric + 1/(abs(hitTableWord[a]))

Any help would be appreciated. As usual with my questions I am sure it is something ridiculously simple that I just do not know about. So thanks for all your patience.


Solution

  • It seems like metric is a class you have defined somewhere, rather than an instance - ie, you have something like:

    class metric(object):
        pass
    

    You would need to call metric() to get an instance of it. Note that you'll continue to get a very similar error if metric doesn't define __add__.

    Likewise, you may have inadvertently done:

    metric = someclass
    

    when you meant:

    metric = someclass()
    

    Either way, the error message is saying that metric contains a class, and Python doesn't know how to add classes to floats (or, for that matter, to anything much).

    Also:

    for a in range (0, len(hitTableWord)):
    

    Is something you usually don't need to do in Python. Here you're using it because you need to access the relevant element of both hitTableWord and hitTableNear - you can do this more idiomatically as:

    for word, near in zip(hitTableWord, hitTableNear):