类型错误:'<''State' 和 'State' PYTHON 3 的实例之间不支持 [英] TypeError: '<' not supported between instances of 'State' and 'State' PYTHON 3
问题描述
我正在尝试使用队列类中的 PriorityQueue.但是,我在将自定义对象放入我的 PQ 时遇到了问题.我已经实现了下面的 __cmp__
函数:
I am trying to utilize a PriorityQueue from the queue class. However, i'm having issues putting custom objects into my PQ. I have implemented the __cmp__
function below:
def __cmp__(self, other):
return (self.priority > other.priority) - (self.priority < other.priority)
我希望 PriorityQueue 按照我的 init 函数中指定的优先级字段排序:
I want the PriorityQueue to be sorted by the priority field, as assigned in my init function:
def __init__(self, board, priority=0):
self.priority = priority
# Other logic
然而,当我运行代码将一个 State 对象插入到 PQ 中时,我得到这个错误:TypeError: '<''State' 和 'State' 的实例之间不支持
However, when I run the code to insert a State object into the PQ, I get this error: TypeError: '<' not supported between instances of 'State' and 'State'
这是运行 PQ 的代码.
Here is the code that runs the PQ.
if op.precond(S):
new_state = op.state_transf(S)
if not (OPEN.queue.__contains__(new_state)) and not (new_state in CLOSED):
GVALUES[Problem.hash(new_state)] = get_distance_value(op, new_state)
HEUR_VALUES[Problem.hash(new_state)] = get_AStar_value(new_state)
print("NEW STATE: " + str(new_state))
OPEN.put(new_state)
print("OPEN: " + str(OPEN.queue))
其中 OPEN 是优先队列.
Where OPEN is the priorityQueue.
任何帮助将不胜感激...因为将值插入 PQ 应该非常简单.
Any help would be greatly appreciated... as it should be pretty straightforward to insert a value into a PQ.
推荐答案
在 Python 3 中你需要定义 __lt__
和 __eq__
而不是 __cmp__
>.
In Python 3 you need to define __lt__
and __eq__
instead of __cmp__
.
参见 https://docs.python.org/3.1/library/stdtypes.html#comparisons.
这篇关于类型错误:'<''State' 和 'State' PYTHON 3 的实例之间不支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!