尝试对字典中的值求和时出现以下错误。我希望得到总和(即 15),但是却抛出了一个错误。
这是一个错误吗?
IPython QtConsole 3.1.0 Python 2.7.10 |Continuum Analytics, Inc.| (默认,2015 年 5 月 28 日,17:04:42)
d = {'1': 1, '2': 2 , '3': 3, '4': 4, '5': 5}
>>> sum(d.values())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-4babd535f17a> in <module>()
----> 1 sum(d.values())
TypeError: 'int' object is not callable
请您参考如下方法:
您在代码中命名了一个指向 int 的变量 sum,因此您实际上是在尝试调用它而不是 sum 函数。只需添加一个 del sum 然后再试一次代码。 一个很好的例子,说明为什么你不应该隐藏内置函数名称。
In [24]: sum = 4
In [25]: sum((1,2))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-a2ca1bd9c959> in <module>()
----> 1 sum((1,2))
TypeError: 'int' object is not callable
In [26]: del sum
In [27]: sum((1,2))
Out[27]: 3
