Python 类型错误:“dict”对象在使用 dict() 时不可调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41605525/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:18:48  来源:igfitidea点击:

TypeError: 'dict' object is not callable while using dict( )

python

提问by Masquerade0097

I was using Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 , when i ran the folllowing code in it the corresponding error is shown .I searched a lot about this but am unable to find why is it so

我在 linux2 上使用 Python 2.7.12(默认,2016 年 11 月 19 日,06:48:10)[GCC 5.4.0 20160609],当我在其中运行以下代码时,会显示相应的错误。我对此进行了很多搜索但我无法找到为什么会这样

>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

回答by Right leg

In a fresh interpreter:

在一个新的解释器中:

>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
>>> bob
{'age': 42, 'pay': '10000', 'job': 'dev', 'name': 'bob smith'}

However, you are getting a TypeError:

但是,您将获得TypeError

TypeError: 'dict' object is not callable

类型错误:“dict”对象不可调用

This error you get tells you that yourdictis not callable.

你得到的这个错误告诉你dict是不可调用的。

Since mydictis callable when I open a fresh interpreter, it means that yourdictis different.

因为当我打开一个新的解释器时mydict是可调用的,这意味着dict的不同。

Most likely, you defined a dictvariable, which overrode the built-in dict. Look for the

最有可能的是,您定义了一个dict变量,该变量覆盖了内置的dict. 寻找

dict = {...}

line, and rename your variable.

行,并重命名您的变量。

As pointed out by @Rob?, don't use built-in names for your variables. Especially avoid the tempting str, list, and so on.

正如@Rob指出的那样?, 不要为变量使用内置名称。尤其要避免诱人的strlist、 等。

回答by Rob?

On a previous line in that interactive session, you have rebound the dictname to some variable. Perhaps you have a line like dict={1:2}or dict=dict(one=1, two=2).

在该交互式会话的前一行中,您已将dict名称重新绑定到某个变量。也许你有一行像dict={1:2}dict=dict(one=1, two=2)

Here is one such session:

这是一个这样的会议:

>>> dict=dict(one=1)
>>> bob=dict(name='bob smith',age=42,pay='10000',job='dev')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> 

As a general rule, one should not use built-in type names as variable names, to prevent this error.

作为一般规则,不应使用内置类型名称作为变量名称,以防止出现此错误。

回答by Peter Gottesman

edit: Ignore this, I am told this is bad practice.

编辑:忽略这一点,有人告诉我这是不好的做法。

As mgilson stated, the issue is likely that you have a variable called dict. The solution to this would be to run

正如 mgilson 所说,问题很可能是您有一个名为 dict 的变量。解决这个问题的方法是运行

del dict

which deletes the variable by that name.

删除该名称的变量。