Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 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)
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)
–
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 )
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.