在Python中使用对象作为列表索引

Shn*_*ick 2 python overriding class

我想知道是否可以使用对象来访问列表中的特定值。

例如,采用以下代码:

class Node:
    def __init__(self, label):
        self.label = label

    def __int__(self):
        return int(self.label)

distances = [10, 20, 30, 40, 50, 60]

node = Node("2")
print(distances[node]) # I expected this to be treated as distances[2]
Run Code Online (Sandbox Code Playgroud)

这将产生错误,因为node它不是有效的索引distances[node]。我希望通过__int__Node类中定义它将节点隐式转换为整数,然后将其视为有效索引。

因此,我想知道是否有一种方法可以进行以下工作(也许通过重写某种方法?):

print(distances[node])  # Desired Output: 30
Run Code Online (Sandbox Code Playgroud)

无需执行以下操作:

print(distances[int(node)])
Run Code Online (Sandbox Code Playgroud)

Akh*_*tra 5

您可以继承int类型并相应地重写。

class Node(int):
    def __init__(self, label):
        self.label = label

    def __int__(self):
        return int(self.label)


distances = [10, 20, 30, 40, 50, 60]

node = Node("2")

print(distances[node])
Run Code Online (Sandbox Code Playgroud)