简体   繁体   English

TypeError: 'type' object 在索引到字典时不可订阅

[英]TypeError: 'type' object is not subscriptable when indexing in to a dictionary

I have multiple files that I need to load so I'm using a dict to shorten things.我有多个文件需要加载,所以我使用dict来缩短文件。 When I run I get a当我跑步时,我得到一个

TypeError: 'type' object is not subscriptable 

Error.错误。 How can I get this to work?我怎样才能让它工作?

m1 = pygame.image.load(dict[1])
m2 = pygame.image.load(dict[2])
m3 = pygame.image.load(dict[3])
dict = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
playerxy = (375,130)
window.blit(m1, (playerxy))

Normally Python throws NameError if the variable is not defined:通常,如果未定义变量,Python 会抛出NameError

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.但是,您设法偶然发现了 Python 中已经存在的名称。

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.因为dict是 Python 中内置类型的名称,所以您看到的似乎是一条奇怪的错误消息,但实际上并非如此。

The type of dict is a type . dict的类型是type All types are objects in Python. Python 中的所有类型都是对象。 Thus you are actually trying to index into the type object.因此,您实际上是在尝试对type对象进行索引。 This is why the error message says that the "'type' object is not subscriptable."这就是错误消息显示“'type' 对象不可下标”的原因。

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that.请注意,您可以盲目地分配dict名称,但您真的不想这样做。 It's just going to cause you problems later.只会在以后给你带来麻烦。

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them.问题的真正根源是您必须在尝试使用它们之前分配变量。 If you simply reorder the statements of your question, it will almost certainly work:如果您只是重新排列问题的陈述,它几乎肯定会起作用:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

你应该更新到python >= 3.9 ,一切都会很好

When I stumbled across this error, I had this function:当我偶然发现这个错误时,我得到了这个 function:

def trainByDistribution(xs: pd.DataFrame, ys: pd.DataFrame, step) -> tuple[float]:

My idea was to create a function that takes two pandas dataframes and an integer and would return a tuple of floating-pointing numbers.我的想法是创建一个 function,它采用两个 pandas 数据帧和一个 integer,并将返回一个浮点数元组。

Like other answers have stated, in Python everything is objects, even classes themselves.就像其他答案所说的那样,在 Python 中,一切都是对象,甚至是类本身。 Classes are in turn blueprint objects that can be used to generate new objects, and consequently classes can be assigned to variables, passed as arguments and programmatically constructed with type() function.类又是可用于生成新对象的蓝图对象,因此可以将类分配给变量,作为 arguments 传递并使用type() function 以编程方式构造。

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return str(name) + str(age)

This class is equivalent to this:这个 class 等同于:

def __init__(self, name, age):
    self.age = age
    self.name = name
def  __str__(self):
     return str(name) + str(age)
Person = type("Person, ("object",), {"__init__": __init__,
            "__str__": __str__})

This error "object is not subscriptable" appears when you pass to a function an object that doesn't support accessing values by indexing (doesn't overload the [] operator).当您将 function 和 object 传递给不支持通过索引访问值(不重载 [] 运算符)的 function 时,会出现此错误“对象不可订阅”。 Since the type of all classes is <class "type"> :由于所有类的类型都是<class "type">

>>> type(Person)
<class "type">

then type object is not subscriptable means you pass class instead of an actual object. This could be more tricky though, in my function above I passed valid dataframes, and my error appeared because I attempted to annotate the return type as tuple[float] , and while this syntax should be legal to my knowledge, the interpreter understood this expression as if I wanted to index the tuple class itself.然后键入 object 不可订阅意味着您传递 class 而不是实际的 object。不过这可能更棘手,在我上面的 function 中我传递了有效的数据帧,并且我的错误出现是因为我试图将返回类型注释为tuple[float] ,虽然据我所知这个语法应该是合法的,但解释器理解这个表达式,就好像我想索引元组 class 本身一样。

Conclusions结论

This error appears when:在以下情况下会出现此错误:

  • you pass class instead of an actual object to a function argument;您将 class 而不是实际的 object 传递给 function 参数;
  • you use the class name to index anything, including naming variables with class names.您使用 class 名称来索引任何内容,包括具有 class 名称的命名变量。

You can take a look at this tutorial by mCoding to find out more about classes as objects.您可以通过 mCoding 查看本教程,以了解有关类作为对象的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM