我想知道是否可以使用对象来访问列表中的特定值。
例如,采用以下代码:
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]
这会产生错误,因为 node
不是 distances[node]
的有效索引。我希望通过在我的 Node
类中定义 __int__
,它将隐式地将节点转换为整数,然后可以将其视为有效索引。
所以,我想知道是否有一种方法可以完成以下工作(也许通过覆盖某种方法?):
print(distances[node]) # Desired Output: 30
无需执行以下操作:
print(distances[int(node)])
最佳答案
您可以子类化 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])
关于python - 在 Python 中使用对象作为列表索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56251503/