'MyClass' object has no attribute '__getitem__'

Question:

I have a class like this one:

class MyClass(object):
    def __init__(self, id, a, b, c):
        self.myList     = []
        self.id         = id
        self.a          = a
        self.b          = b
        self.c          = c

    def addData(self, data):
        self.myList.append(data)

In my main code, I create a list of MyClass instances called myClassList. In a line I have to check if an item with a given id already exists. I do it in this way:

id = 'foo' # in real code is set dynamically 
recent_item = next( (item for item in myClassList if item['id'] == id), None )

The second line in that code gives this error:

‘MyClass’ object has no attribute '__getitem__'

How can I fix?

Asked By: floatingpurr

||

Answers:

item is not a dictionary but a class so it has different syntax for accessing members. Access id this way instead:

item.id
Answered By: hiro protagonist

Like the error suggests, you can only use subscript on class instances, if the class defines a __getitem__() instance method.

As id is an attribute of the instance, you should use – item.id instead of item['id'] .

Example –

recent_item = next( (item for item in myClassList if item.id == id), None )
Answered By: Anand S Kumar

id is an attribute of MyClass instance, you have to access it as item.id

recent_item = next( (item for item in myClassList if item.id == id), None )
Answered By: Anbarasan

If you actually wanted to be able to access your attributes using inst["attr"] and to explain your error, you would need to add a __getitem__ to you class:

class MyClass(object):
    def __init__(self, id, a, b, c):
        self.myList     = []
        self.id         = id
        self.a          = a
        self.b          = b
        self.c          = c

    def addData(self, data):
        self.myList.append(data)

    def __getitem__(self, item):
        return getattr(self, item)
Answered By: Padraic Cunningham

As others have noted, you can simply use

item.id

However, sometimes you do need to use this syntax if you are accessing a field dynamically:

item[dynamicField]

In that case, you can use the __getitem__() syntax as Anand suggested, however it is safer to use python’s wrapper for __getitem__:

getattr(item, dynamicField)
Answered By: Aidan Hoolachan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.