Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'MyClass' object has no attribute '__getitem__'

Tags:

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?

like image 379
floatingpurr Avatar asked Aug 04 '15 10:08

floatingpurr


1 Answers

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

item.id 
like image 147
hiro protagonist Avatar answered Jan 11 '23 22:01

hiro protagonist