python - 棘手的 : 'dict' object is not callable

标签 python dictionary

这是一个棘手的错误,您可能会在使用 Python 的字典中遇到这种错误:

dict = {'a':5,'c':5}
#Typing some codes

在程序的某个时刻,您决定创建一个空字典:

new_dic = dict()

你得到这个回溯:

Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'dict' object is not callable

你能告诉我这是 Python 中的错误还是我们在使用内置函数时必须小心,不要预先为某些变量分配它们的名称?

最佳答案

您遇到的情况称为“阴影”。您已经在某个命名空间(模块的全局命名空间或函数的局部命名空间)中创建了一个对象,该对象与内置 dict 类型同名。这会阻止您以通常的方式访问内置的 dict

仍然可以完成它,但需要付出更多的努力。 builtins(或 Python 2 中的 __builtin__)模块包含所有通常可直接访问的内置对象。因此,要制作空字典,您可以执行以下操作:

import builtins

dict = whatever

newdic = builtins.dict()

但是...避免为您自己的对象使用名称 dict 可能是一个更好的主意。

关于python - 棘手的 : 'dict' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33546859/

相关文章:

python - Pandas 数据框 : how to apply describe() to each group and add to new columns?

python - 在Python中使用Structure和char数组

python-3.x - 将字典值添加到列表中?

具有多个键的 Java Map

Java的hashmap : Is keys() indeed missing?

python - Keras:将元数据连接到 CNN 中

python - 对整数 numpy 数组执行按位测试

python - 单语句斐波那契

JSON 到 Excel 的转换,通过使用 go lang 映射数据结构不会每次都产生相同的输出

android - 当我不知道 key 时如何从 sharedpreference 中获取值