Shnick
Shnick

Reputation: 1391

Use object as list index in Python

I'm wondering whether it is possible to use an object to access a particular value in a list.

For instance, take the following code:

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]

This will give an error, as node is not a valid index for distances[node]. I was hoping that by defining __int__ in my Node class that it would implicitly cast the node to an integer, which could then be treated like a valid index.

So, I'm wondering if there is a way in which I can make the following work (perhaps by overriding a method of some sort?):

print(distances[node])  # Desired Output: 30

without having to do something like the following:

print(distances[int(node)])

Upvotes: 3

Views: 249

Answers (2)

Akhil Batra
Akhil Batra

Reputation: 610

You can subclass int type and override accordingly.

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])

Upvotes: 6

Demont Zhang
Demont Zhang

Reputation: 224

You should us distance[node.id] since you want to call the attribute id of the object node.

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

    def __int__(self):
        return self.id

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

node = Node(2)

In [1] : print(distances[node.id]) # I expected this to be treated as distances[2]
Out[1] : 30

Upvotes: 1

Related Questions