类型错误:“节点”和“节点”的实例之间不支持“<”

时间:2021-02-14 18:15:53

标签: python python-3.x

我使用的是 Python 3.8。我有以下列表:

[['Bangalore', 116.0], ['Mumbai', 132.0], ['Kolkata', 234.0]]

然后我创建了一个节点并添加到 successors 列表中,如下所示:

successors = [<__main__.Node object at 0x7f89582eb7c0>, <__main__.Node object at 0x7f89582eb790>, <__main__.Node object at 0x7f89582eb7f0>]

我创建了一个边缘列表并添加了每个后继节点。然后根据距离值对其进行排序。我收到错误 - '<' not supported between instances of 'node' and 'node'

for succ_node in successors:
    fringe.append(succ_node)
fringe.sort() <- Error Here

这是我的节点类:

class Node:
    def __init__(self, parent, name, g):
        self.parent = parent
        self.name = name
        self.g = g

我做错了什么?

1 个答案:

答案 0 :(得分:3)

在python 3中,你必须为类定义比较方法,例如如下:

class Node:
    def __init__(self, parent, name, g):
        self.parent = parent
        self.name = name
        self.g = g

    def __eq__(self, other):
        return (self.name == other.name) and (self.g == other.g)

    def __ne__(self, other):
        return not (self == other)

    def __lt__(self, other):
        return (self.name < other.name) and (self.g < other.g)

    def __gt__(self, other):
        return (self.name > other.name) and (self.g > other.g)

    def __le__(self, other):
        return (self < other) or (self == other)

    def __ge__(self, other):
        return (self > other) or (self == other)

有时并非所有这些方法都需要 - 这主要取决于您将使用哪种比较。

有更详细的说明:https://portingguide.readthedocs.io/en/latest/comparisons.html