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)
Author by
Jetse
Updated on June 04, 2022Comments
-
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 almost 11 yearsJust checked,
__int__(self)
will work well. useint(MyObject)
casting method to convert your object to integer. -
RoadieRich almost 11 yearsThat will give you a NameError on score. You need to use a getter, something like
lambda s: s.score
(oroperator.attrgetter("score")
).