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

Jay*_*kur 1 python python-3.x

我正在使用Python 3.8。我有以下清单:

[['Bangalore', 116.0], ['Mumbai', 132.0], ['Kolkata', 234.0]]
Run Code Online (Sandbox Code Playgroud)

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

successors = [<__main__.Node object at 0x7f89582eb7c0>, <__main__.Node object at 0x7f89582eb790>, <__main__.Node object at 0x7f89582eb7f0>]
Run Code Online (Sandbox Code Playgroud)

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

for succ_node in successors:
    fringe.append(succ_node)
fringe.sort() <- Error Here
Run Code Online (Sandbox Code Playgroud)

这是我的节点类:

class Node:
    def __init__(self, parent, name, g):
        self.parent = parent
        self.name = name
        self.g = g
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Vil*_*ech 5

在 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)
Run Code Online (Sandbox Code Playgroud)

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

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