【问题标题】:Why does the 'int' object is not callable error occur when using the sum() function? [duplicate]为什么在使用 sum() 函数时会出现 'int' object is not callable 错误? [复制]
【发布时间】:2012-06-26 06:28:29
【问题描述】:

我试图弄清楚为什么在范围上使用 sum 函数时会出错。

代码如下:

data1 = range(0, 1000, 3)
data2 = range(0, 1000, 5)
data3 = list(set(data1 + data2)) # makes new list without duplicates
total = sum(data3) # calculate sum of data3 list's elements
print total

这是错误:

line 8, in <module> total2 = sum(data3)
TypeError: 'int' object is not callable

我找到了这个错误的解释:

在 Python 中,“可调用”通常是一个函数。该消息意味着您将数字(一个>“int”)视为一个函数(一个“可调用”),所以Python不知道该做什么,所以它>停止。

我还读到 sum() 能够用于列表,所以我想知道这里出了什么问题?

我刚刚在 IDLE 模块中尝试过,效果很好。但是,它在 python 解释器中不起作用。有什么想法吗?

【问题讨论】:

  • 这对我来说非常有效......你在调用函数之前命名了一个变量sum 吗?
  • 刚刚编辑过的原件。我正在使用 IDE。正如您所提到的,在 IDLE 中工作。 IDE 正在运行 Python 2.7。这很奇怪。
  • 您说“它在 IEP 中不起作用”。什么是 IEP?
  • Python 的交互式编辑器。 code.google.com/p/iep
  • 您实际上不需要将您的集合转换回列表...sum() 将处理任何数字序列。

标签: python sum python-2.7 callable


【解决方案1】:

您可能将“sum”函数重新定义为整数数据类型。所以它正确地告诉你整数不是你可以传递范围的东西。

要解决此问题,请重新启动您的解释器。

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168

如果你隐藏 sum 内置函数,你会得到你所看到的错误

>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

另外,请注意 sum 可以在 set 上正常工作,无需将其转换为 list

【讨论】:

    【解决方案2】:

    这意味着在你的代码的其他地方,你有类似的东西:

    sum = 0
    

    它用 int (不是)遮蔽了内置总和(可调用的)。

    【讨论】:

    • 显示的代码是整个程序。我希望它是那么简单。还有其他想法吗?
    • @mattste 重启你的 python 解释器并尝试一下。
    • 现在工作。感谢您的帮助!
    【解决方案3】:

    在解释器中很容易重新启动它并修复此类问题。如果您不想重新启动解释器,还有另一种方法可以修复它:

    Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
    [GCC 4.4.5] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> l = [1,2,3]
    >>> sum(l)
    6
    >>> sum = 0 # oops! shadowed a builtin!
    >>> sum(l)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not callable
    >>> import sys
    >>> sum = sys.modules['__builtin__'].sum # -- fixing sum
    >>> sum(l)
    6
    

    如果您碰巧为任何其他内置函数赋值,例如 dictlist,这也会派上用场

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2021-06-23
      • 2020-12-15
      • 2021-10-22
      相关资源
      最近更新 更多