当前位置: 代码迷 >> 综合 >> AttributeError: Foo instance has no attribute '__getitem__'
  详细解决方案

AttributeError: Foo instance has no attribute '__getitem__'

热度:99   发布时间:2023-12-21 17:54:18.0

一个object是不能像dict那样通过[]访问的,比如下面这段代码会报错:

>>> class Foo():
...     id = 1
... 
>>> 
>>> f = Foo()
>>> f[id]
Traceback (most recent call last):File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute '__getitem__'

 正确的做法是通过getattr(obj, name)

  相关解决方案