Python 'MyClass' 对象没有属性 '__getitem__'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31807172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'MyClass' object has no attribute '__getitem__'
提问by floatingpurr
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:
在我的主代码中,我创建了一个名为myClassList
. 在一行中,我必须检查具有给定的项目是否id
已经存在。我是这样做的:
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__'
“MyClass”对象没有属性
'__getitem__'
How can I fix?
我该如何解决?
采纳答案by hiro protagonist
item
is not a dictionary but a class so it has different syntax for accessing members. Access id
this way instead:
item
不是字典而是一个类,因此它具有不同的访问成员的语法。以id
这种方式访问:
item.id
回答by Anand S Kumar
Like the error suggests, you can only use subscript on class instances, if the class defines a __getitem__()
instance method.
就像错误提示的那样,如果类定义了__getitem__()
实例方法,则只能在类实例上使用下标。
As id
is an attribute of the instance, you should use - item.id
instead of item['id']
.
作为id
实例的一个属性,您应该使用 -item.id
而不是item['id']
。
Example -
例子 -
recent_item = next( (item for item in myClassList if item.id == id), None )
回答by Anbarasan
id
is an attribute of MyClass instance, you have to access it as item.id
id
是 MyClass 实例的一个属性,你必须访问它 item.id
recent_item = next( (item for item in myClassList if item.id == id), None )
回答by Padraic Cunningham
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:
如果您确实希望能够使用inst["attr"]
并解释您的错误来访问您的属性,则需要__getitem__
向您的类中添加一个:
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)
回答by Aidan Hoolachan
As others have noted, you can simply use
正如其他人所指出的,您可以简单地使用
item.id
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__:
在这种情况下,您可以按照 Anand 的建议使用 __getitem__() 语法,但是使用 python 的 __getitem__ 包装器更安全:
getattr(item, dynamicField)