添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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?

...you could implement __getitem__! Alternatively, use item.id instead of item['id']. Note also that you're assigning self.id = a, which is likely not what you intended, and aren't compliant with the style guide. – jonrsharpe Aug 4, 2015 at 10:45

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)
                Sorry to beat a dead bush, but I think it would be correct to call it a property in this case? stackoverflow.com/a/7374831/6743506
– Bryant James
                Dec 15, 2017 at 14:43

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.