python 在列表上使用 sum 函数时,“int”对象不可调用

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

'int' object is not callable when using the sum function on a list

pythonlist

提问by Matt Phillips

coinCount = [2 for i in range(4)]
total = sum(coinCount)

This gives me

这给了我

TypeError: 'int' object is not callable

I don't understand why because

我不明白为什么因为

print type(coinCount)

Gives me

给我

type <'list'>

回答by Alex Martelli

You no doubt used the identifier sumpreviously in your code as a local variable name, and the last value you bound to it was an int. So, in that code snippet, you're trying to call the int. print sumjust before you try calling it and you'll see, but code inspection will probably reveal it faster.

毫无疑问sum,您之前在代码中使用了标识符作为局部变量名,并且您绑定到它的最后一个值是int. 因此,在该代码段中,您尝试调用int. print sum就在您尝试调用它之前,您会看到,但代码检查可能会更快地显示它。

This kind of problem is why expert Pythonistas keep telling newbies over and over "don't use builtin names for your own variables!" even when it's apparently not hurting a specific code snippet: it's a horrible habit, and a bug just waiting to happen, if you use identifiers such as sum, file, list, etc, as your own variables or functions!-)

这种问题就是为什么专家 Pythonistas 一遍又一遍地告诉新手“不要为自己的变量使用内置名称!” 即使它显然不是伤害特定的代码片段:这是一个可怕的习惯,错误只是等待发生,如果你使用的标识符,例如sumfilelist!,等等,作为自己的变量或函数- )

回答by Nick the coder

I'd like to add on to what Alex Martelli said by saying don't use sum as a variable name but if you're program is too long already or you're using idle and you don't want to start over you can do

我想补充一下 Alex Martelli 所说的不要使用 sum 作为变量名,但是如果你的程序已经太长或者你正在使用空闲并且你不想重新开始,你可以做

sum2 = sum
del sum

to transfer the value of sum into sum2 (if necessary) and delete the variable sum (allowing you to continue working with the sum function)

将 sum 的值转移到 sum2(如有必要)并删除变量 sum(允许您继续使用 sum 函数)