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?
item
is not a dictionary but a class so it has different syntax for accessing members. Access id
this way instead:
item.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With