类型错误:“列表”对象在 python 中不可调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31087111/
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
TypeError: 'list' object is not callable in python
提问by khan shah
I am novice to Python and following a tutorial. There is an example of list
in the tutorial :
我是 Python 新手,正在学习教程。list
教程中有一个例子:
example = list('easyhoss')
Now, In tutorial, example= ['e','a',...,'s']
. But in my case I am getting following error:
现在,在教程中,example= ['e','a',...,'s']
. 但就我而言,我收到以下错误:
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Please tell me where I am wrong. I searched SO thisbut it is different.
请告诉我我错在哪里。我搜索了这个,但它是不同的。
采纳答案by Eli Korvigo
Seems like you've shadowed the builtin name list
pointing at a class by the same name pointing at its instance. Here is an example:
似乎您已经list
用指向其实例的相同名称隐藏了指向类的内置名称。下面是一个例子:
>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in dictionaries (namespaces are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced.
我相信这是相当明显的。Python 将对象名称(函数和类也是对象)存储在字典中(命名空间实现为字典),因此您几乎可以在任何范围内重写任何名称。它不会显示为某种错误。您可能知道 Python 强调“特殊情况不足以打破规则”。您所面临的问题背后有两个主要规则。
Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest namespaces. As I've already mentioned, namespaces are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace. In fact it's just a local namespace with respect to that particular module.
Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a
NameError
. Builtin functions and classes reside in a special high-order namespace__builtins__
. If you declare a variable namedlist
in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is__builtins__
). Similarly, suppose you create a variablevar
inside a function in your module, and another variablevar
in the module. Then, if you referencevar
inside the function, you will never get the globalvar
, because there is avar
in the local namespace - the interpreter has no need to search it elsewhere.
命名空间。Python 支持嵌套命名空间。理论上,您可以无休止地嵌套命名空间。正如我已经提到的,名称空间基本上是名称和对相应对象的引用的字典。您创建的任何模块都有自己的“全局”命名空间。事实上,它只是一个相对于该特定模块的本地命名空间。
范围。当您引用一个名称时,Python 运行时会在本地命名空间(相对于引用)中查找它,如果这样的名称不存在,它会在更高级别的命名空间中重复尝试。这个过程一直持续到没有更高的命名空间为止。在这种情况下,您会得到一个
NameError
. 内置函数和类驻留在一个特殊的高阶命名空间中__builtins__
。如果list
在模块的全局命名空间中声明一个变量,解释器将永远不会在更高级别的命名空间(即__builtins__
)中搜索该名称。同样,假设您var
在模块中的函数内创建了一个变量,并在模块中创建了另一个变量var
。然后,如果你var
在函数内部引用,你将永远不会得到全局var
,因为var
在本地命名空间中有一个- 解释器不需要在其他地方搜索它。
Here is a simple illustration.
这是一个简单的说明。
>>> example = list("abc") # Works fine
# Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
# Python looks for "list" and finds it in the global namespace.
# But it's not the proper "list".
# Let's remove "list" from the global namespace
>>> del list
# Since there is no "list" in the global namespace of the module,
# Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm or Atom with Python plugins) that highlights name shadowing to avoid such errors.
因此,如您所见,Python 内置函数并没有什么特别之处。你的情况只是普遍规则的一个例子。您最好使用突出显示名称阴影的 IDE(例如免费版本的 PyCharm 或带有 Python 插件的 Atom)以避免此类错误。
You might as well be wondering what is a "callable", in which case you can read the following post: https://stackoverflow.com/a/111255/3846213. list
, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list
instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation(quite conveniently, the same page covers namespaces and scoping).
您可能想知道什么是“可调用”,在这种情况下,您可以阅读以下帖子:https: //stackoverflow.com/a/111255/3846213。list
,作为一个类,是可调用的。调用类会触发实例构建和初始化。一个实例也可能是可调用的,但list
实例不是。如果您对类和实例之间的区别更加困惑,那么您可能需要阅读文档(非常方便,同一页面涵盖了命名空间和作用域)。
If you want to know more about builtins, please read the answer by Christian Dean.
如果您想了解有关内置函数的更多信息,请阅读 Christian Dean 的回答。
P.S.
聚苯乙烯
When you start an interactive Python session you create a temporary module.
当您启动交互式 Python 会话时,您将创建一个临时模块。
回答by Oded Regev
For me it was a flask serverreturning some videos
array (which I expected to be in json format..)
对我来说,它是一个Flask 服务器返回一些videos
数组(我希望它是 json 格式..)
adding json.dumps(videos)
fixed this issue
添加json.dumps(videos)
修复了这个问题
回答by user1767754
If you are in a interactive session and don't want to restart you can remove the shadowing with
如果您处于交互式会话中并且不想重新启动,则可以使用
del list
回答by Kevin
You may have used built-in name 'list' for a variable in your code. If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal. In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shit+Tab, and check if Docstring shows it as an empty list.
您可能在代码中为变量使用了内置名称“list”。如果您使用的是 Jupyter 笔记本,有时即使您将该变量的名称从“列表”更改为不同的名称并重新运行该单元格,您仍然可能会收到错误消息。在这种情况下,您需要重新启动内核。为了确保名称已更改,请在创建列表对象时单击“列表”一词并按 Shit+Tab,然后检查 Docstring 是否将其显示为空列表。
回答by Christian Dean
Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.
在您完全理解错误的含义以及如何解决之前,了解 Python 中的内置名称是什么很重要。
What is a built-in name?
什么是内置名称?
In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a functionor classobject. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.
在 Python 中,内置名称是Python 解释器已经分配了预定义值的名称。该值可以是函数或类对象。这些名称在默认情况下始终可用,无论范围如何。分配给这些名称的一些值代表 Python 语言的基本类型,而另一些则简单有用。
As of the latest version of Python - 3.6.2- there are currently 61built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.
截至最新版本的 Python - 3.6.2- 目前有61 个内置名称。完整的名称列表以及如何使用它们,可以在文档部分内置函数中找到。
An important point to note however, is that Python will notstop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.
然而,需要注意的重要一点是,Python不会阻止您重新分配内置名称。内置名称不是保留的,Python 也允许将它们用作变量名称。
Here is an example using the dict
built-in:
这是使用dict
内置的示例:
>>> dict = {}
>>> dict
{}
>>>
As you can see, Python allowed us to assign the dict
name, to reference a dictionary object.
如您所见,Python 允许我们分配dict
名称,以引用字典对象。
What does "TypeError: 'list' object is not callable" mean?
“TypeError:'list' 对象不可调用”是什么意思?
To put it simply, the reason the error is occurring is because you re-assignedthe builtin namelist
in the script:
简单地说,发生错误的原因是因为您在脚本中重新分配了内置名称list
:
list = [1, 2, 3, 4, 5]
When you did this, you overwrote the predefined value of the built-in name. This means you can no longer use the predefined value of list
, which is a class object representing Python list.
当您这样做时,您覆盖了内置 name 的预定义值。这意味着您不能再使用 的预定义值list
,它是表示 Python 列表的类对象。
Thus, when you tried to use the list
class to create a new list from a range
object:
因此,当您尝试使用list
该类从range
对象创建新列表时:
myrange = list(range(1, 10))
Python raised an error. The reason the error says "'list' object is not callable", is because as said above, the name list
was referring to a list object. So the above would be the equivalent of doing:
Python 引发了错误。错误显示“'list' 对象不可调用”的原因是因为如上所述,该名称list
指的是一个列表对象。所以上面的内容相当于做:
[1, 2, 3, 4, 5](range(1, 10))
Which of course makes no sense. You cannot call a list object.
这当然没有意义。您不能调用列表对象。
How can I fix the error?
我该如何修复错误?
Suppose you have code such as the following:
假设您有如下代码:
list = [1, 2, 3, 4, 5]
myrange = list(range(1, 10))
for number in list:
if number in myrange:
print(number, 'is between 1 and 10')
Running the above code produces the following error:
运行上面的代码会产生以下错误:
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: 'list' object is not callable
If you are getting a similar error such as the one above saying an "object is not callable", chances are you used a builtin name as a variable in your code. In this case and other cases the fix is as simple as renaming the offending variable. For example, to fix the above code, we could rename our list
variable to ints
:
如果您遇到类似的错误,例如上面所说的“对象不可调用”,那么您很可能在代码中使用了内置名称作为变量。在这种情况下和其他情况下,修复就像重命名有问题的变量一样简单。例如,要修复上述代码,我们可以将list
变量重命名为ints
:
ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))
for number in ints: # Renamed "list" to "ints"
if number in myrange:
print(number, 'is between 1 and 10')
PEP8- the official Python style guide - includes many recommendations on naming variables.
PEP8- 官方 Python 风格指南 - 包括许多关于命名变量的建议。
This is a very common error new and old Python users make. This is why it's important to always avoid using built-in names as variables such as str
, dict
, list
, range
, etc.
这是新老 Python 用户常犯的错误。这就是为什么总是避免使用很重要内置的名称作为变量,如str
,dict
,list
,range
,等。
Many linters and IDEs will warn you when you attempt to use a built-in name as a variable. If your frequently make this mistake, it may be worth your time to invest in one of these programs.
当您尝试使用内置名称作为变量时,许多 linter 和 IDE 会警告您。如果您经常犯这个错误,那么花时间投资其中一个程序可能是值得的。
I didn't rename a built-in name, but I'm still getting "TypeError: 'list' object is not callable". What gives?
我没有重命名内置名称,但我仍然收到“TypeError: 'list' object is not callable”。是什么赋予了?
Another common cause for the above error is attempting to index a list using parenthesis (()
) rather than square brackets ([]
). For example:
上述错误的另一个常见原因是尝试使用括号 ( ()
) 而不是方括号 ( []
)来索引列表。例如:
>>> lst = [1, 2]
>>> lst(0)
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
lst(0)
TypeError: 'list' object is not callable
For an explanation of the full problem and what can be done to fix it, see TypeError: 'list' object is not callable while trying to access a list.
有关完整问题的说明以及如何修复它,请参阅TypeError: 'list' object is not callable while try to access a list。
回答by U10-Forward
Why does TypeError: 'list' object is not callable
appear?
为什么会TypeError: 'list' object is not callable
出现?
Explanation:
解释:
It is because you defined list
as a variable before (i am pretty sure), so it would be a list, not the function anymore, that's why everyone shouldn't name variables functions, the below is the same as what you're doing now:
这是因为你list
之前定义了一个变量(我很确定),所以它会是一个列表,而不是函数,这就是为什么每个人都不应该命名变量函数,下面和你现在所做的一样:
>>> [1,2,3]()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
[1,2,3]()
TypeError: 'list' object is not callable
>>>
So you need it to be the default function of list
, how to detect if it is? just use:
所以你需要它是 的默认函数list
,如何检测它是否是?只需使用:
>>> list
<class 'list'>
>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>> list()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
list()
TypeError: 'list' object is not callable
>>>
How do i detect whether a variable name is a function? well, just simple see if it has a different color, or use a code like:
如何检测变量名是否是函数?好吧,只是简单地看看它是否有不同的颜色,或者使用如下代码:
>>> 'list' in dir(__builtins__)
True
>>> 'blah' in dir(__builtins__)
False
>>>
After this, you should know why does TypeError: 'list' object is not callable
appear.
在此之后,您应该知道为什么会TypeError: 'list' object is not callable
出现。
Okay, so now...
好的,那么现在...
How to fix this TypeError: 'list' object is not callable
error?
如何修复此TypeError: 'list' object is not callable
错误?
Code:
代码:
You have to either do __builtins__.list()
:
你要么做__builtins__.list()
:
>>> list = [1,2,3]
>>> __builtins__.list()
[]
>>>
Or use []
:
或使用[]
:
>>> list = [1,2,3]
>>> []
[]
>>>
Or remove list
variable from memory:
或者list
从内存中删除变量:
>>> list = [1,2,3]
>>> del list
>>> list()
[]
>>>
Or just rename the variable:
或者只是重命名变量:
>>> lst = [1,2,3]
>>> list()
[]
>>>
P.S. Last one is the most preferable i guess :-)
PS 我猜最后一个是最可取的:-)
There are a whole bunch of solutions that work.
有一大堆有效的解决方案。
References:
参考:
'id' is a bad variable name in Python
How do I use a keyword as a variable name?
How to use reserved keyword as the name of variable in python?
回答by James H
I was getting this error for another reason:
由于另一个原因,我收到此错误:
I accidentally had a blank list created in my __init__
which had the same name as a method I was trying to call (I had just finished refactoring a bit and the variable was no longer needed, but I missed it when cleaning up). So when I was instantiating the class and trying to call the method, it thought I was referencing the list object, not the method:
我不小心创建了一个空白列表,__init__
它与我试图调用的方法同名(我刚刚完成了一点重构,不再需要该变量,但我在清理时错过了它)。因此,当我实例化类并尝试调用该方法时,它认为我引用的是列表对象,而不是方法:
class DumbMistake:
def __init__(self, k, v):
self.k = k
self.v = v
self.update = []
def update(self):
// do updates to k, v, etc
if __name__ == '__main__':
DumbMistake().update('one,two,three', '1,2,3')
So it was trying to assign the two strings to self.update[] instead of calling the update() method. Removed the variable and it all worked as intended. Hope this helps someone.
所以它试图将两个字符串分配给 self.update[] 而不是调用 update() 方法。删除了变量,一切都按预期工作。希望这可以帮助某人。
回答by Joris
In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:
在星期一早上愚蠢的错误联盟中,尝试访问列表中的项目时使用圆括号而不是方括号也会给您相同的错误消息:
l=[1,2,3]
print(l[2])#GOOD
print(l(2))#BAD
TypeError: 'list' object is not callable
类型错误:“列表”对象不可调用
回答by 99 North
to solve the error like this one: "list object is not callable in python"
even you are changing the variable name then please restart the kernelin Python Jutyter Notebook if you are using it or simply restart the IDE.
要解决这样的错误:"list object is not callable in python"
即使您正在更改变量名称,如果您正在使用 Python Jutyter Notebook,请重新启动内核,或者只需重新启动 IDE。
I hope this will work. Thank you!!!
我希望这会奏效。谢谢!!!
回答by George
find out what you have assigned to 'list' by displaying it
通过显示来找出您分配给“列表”的内容
>>> print(list)
if it has content, you have to clean it with
如果它有内容,你必须用
>>> del list
now display 'list' again and expect this
现在再次显示“列表”并期待这个
<class 'list'>
Once you see this, you can proceed with your copy.
一旦你看到这个,你就可以继续你的副本。