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))
4

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.

1

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)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest