在列表上使用sum函数时,不能调用"int"对象 [英] 'int' object is not callable when using the sum function on a list

查看:189
本文介绍了在列表上使用sum函数时,不能调用"int"对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这给了我

TypeError: 'int' object is not callable

我不明白为什么,因为

print type(coinCount)

给我

type <'list'>

推荐答案

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

You no doubt used the identifier sum previously 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 sum just before you try calling it and you'll see, but code inspection will probably reveal it faster.

这种问题就是为什么专家Pythonista总是不断地告诉新手不要对您自己的变量使用内置名称!"即使显然没有伤害到特定的代码段:这是一种可怕的习惯,并且如果您使用诸如sumfilelist之类的标识符作为自己的变量或函数,那么这只是一个等待发生的错误. !-)

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!-)

这篇关于在列表上使用sum函数时,不能调用"int"对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆