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

标签 python class overriding

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

例如,采用以下代码:

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/

相关文章:

python - Plotly:悬停文本字段中的日期格式问题

python - 如何将 python 脚本放在路径上?

c# - 您如何处理具有不同类型结果的重写函数?

Java - 重写>variable<中的paint(Graphics g)方法

python /OpenCV : Computing a depth map from stereo images

python - 覆盖 clean(),数据不可访问

c++ - 通过函数调用 C++ 中的线程更改对象属性

java - 如何获取像 Collection<SomeObject> 这样的通用集合的 java.lang.Class 实例?

java - 不一致的类层次结构

c++ - 继承QTime,自定义时间格式