Omar Khalid
Omar Khalid

Reputation: 354

overloading a class method to be able to index python objects in a list based on their attributes

Imagine that I have a class called foo and its definition is following

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

and I want this to happen


dummylist = [foo(3), foo(4), foo(10)]

# I want to do that if possible

print(dummylist[10]) # and get the last object in the list

What I want is that I have a class with a lot of attributes and I want to have a list of objects of that class and would be able to retrieve a specific object with a value of its attribute.

I know that I can do that with next or list comprehension but I want to do so by indexing the list of object with []

Upvotes: 1

Views: 610

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18106

You could make your own list using collections.UserList:

from collections import UserList 


class myList(UserList):
    def _lookup(self, name):
        for item in self.data:
            if item.id == name:
                return item

    def __getitem__(self, name):
        return self._lookup(name)

    def __call__(self, name):
        return self._lookup(name)


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


dummylist = myList([foo(3), foo(4)])
dummylist.append(foo(10))
print(dummylist(10), dummylist(10).id)
print(dummylist[3], dummylist[3].id)

Out:

<__main__.foo object at 0x104a52460> 10
<__main__.foo object at 0x1049cfa00> 3

Upvotes: 3

Related Questions