python将对象强制转换为int
我正在使用numpy模块检索2d数组中最大值的位置。但是这个2d数组由MyObject组成。现在我得到一个错误: TypeError:无序类型:int()>MyObject() 我试图用以下代码覆盖int函数:python将对象强制转换为int,python,object,casting,integer,Python,Object,Casting,Integer,我正在使用numpy模块检索2d数组中最大值的位置。但是这个2d数组由MyObject组成。现在我得到一个错误: TypeError:无序类型:int()>MyObject() 我试图用以下代码覆盖int函数: def int(self): return self.score 但这并不能解决我的问题。 我是否必须将MyObject的2d数组转换为整数的2d数组,我是否必须扩展Integer对象(如果在python中可以),或者我是否可以用另一种方式重写这个int()函数 [编辑] 完整
def int(self):
return self.score
但这并不能解决我的问题。
我是否必须将MyObject的2d数组转换为整数的2d数组,我是否必须扩展Integer对象(如果在python中可以),或者我是否可以用另一种方式重写这个int()函数
[编辑]
完整对象:
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
我称之为对象的方式:
def traceBack(self):
self.matrix = np.array(self.matrix)
maxIndex = self.matrix.argmax()
print(self.matrix.unravel_index(maxIndex))
max
函数采用应用于元素的键。这就是你放分数的地方
通常:
a = max(my_list, key=score)
尝试使用
...
def __int__(self):
return self.score
...
test = MyObject(0, 0, 10, 0, 0)
print 10+int(test)
# Will output: 20
在MyObject类定义中。请在MyObject
中发布所有相关代码,您将更容易获得帮助。什么是self.score
?如果数组不包含float
或int
数据类型,您希望数组的最大值是多少?这甚至不是覆盖整数转换的方式。。。提示:是的,不管你在做什么,可能无论如何都不会调用它-我不相信Python在比较对象时会试图强制对象为相同的类型。str(self.score)
不是一个int…只要检查一下,\uint(self)
就能很好地工作。使用int(MyObject)
casting方法将对象转换为整数。这将在分数上给您一个名称错误。您需要使用一个getter,类似于lambda s:s.score
(或operator.attrgetter(“score”)
)。