Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python cast object to int

I am using the numpy module to retrieve the position of the maximum value in a 2d array. But this 2d array consists of MyObjects. Now I get the error:

TypeError: unorderable types: int() > MyObject()

I tried to override the int function with this code:

def int(self):
    return self.score

But this does not solve my problem. Do I have to convert my 2d array of MyObjects into a 2d array of integers, do I have to extend the Integer object (if this is possible in python) or can I override this int() function in another way?

[EDIT]

The full object:

class MyObject:
def __init__(self, x, y, score, direction, match):
    self.x = x
    self.y = y
    self.score = score
    self.direction = direction
    self.match = match

def __str__(self):
    return str(self.score)

def int(self):
    return self.score

The way I call this object:

 def traceBack(self):
    self.matrix = np.array(self.matrix)
    maxIndex = self.matrix.argmax()
    print(self.matrix.unravel_index(maxIndex))
like image 931
Jetse Avatar asked May 22 '13 14:05

Jetse


2 Answers

Try to use

...
def __int__(self):
    return self.score
...

test = MyObject(0, 0, 10, 0, 0)
print 10+int(test)

# Will output: 20

in your MyObject class definition.

like image 188
Kostanos Avatar answered Sep 21 '22 17:09

Kostanos


The max function takes a key that is applied on the elements. that's where you put score

Typically :

a = max(my_list, key=score)
like image 22
njzk2 Avatar answered Sep 17 '22 17:09

njzk2