python cast object to int

19,295

Solution 1

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.

Solution 2

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)
Share:
19,295
Jetse
Author by

Jetse

Updated on June 04, 2022

Comments

  • Jetse
    Jetse almost 2 years

    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))
    
  • Kostanos
    Kostanos almost 11 years
    Just checked, __int__(self) will work well. use int(MyObject) casting method to convert your object to integer.
  • RoadieRich
    RoadieRich almost 11 years
    That will give you a NameError on score. You need to use a getter, something like lambda s: s.score (or operator.attrgetter("score")).