
example = list('easyhoss')
现在,在教程中,示例= [‘e’,’a’,…,’s’].但在我的情况下,我得到以下错误:
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
请告诉我我错在哪里.我搜索了SO this,但它是不同的.
>>> 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
我相信这是相当明显的. Python在字典中存储对象名称(函数和类也是对象)(名称空间实现为字典),因此您可以在任何范围内重写几乎任何名称.它不会显示为某种错误.正如您可能知道的那样,Python强调“特殊情况不足以破坏规则”.你面临的问题背后有两个主要规则.
>命名空间. Python支持嵌套命名空间.从理论上讲,你可以无休止地嵌套命名空间.正如我已经提到的,名称空间基本上是名称字典和对相应对象的引用.您创建的任何模块都有自己的“全局”命名空间.实际上,它只是与该特定模块相关的本地命名空间.
>范围.当您引用名称时,Python运行时会在本地名称空间中查找它(相对于引用),如果此名称不存在,它会在更高级别的名称空间中重复尝试.此过程将继续,直到没有更高的命名空间.在这种情况下,您会收到NameError.内置函数和类驻留在一个特殊的高阶命名空间__builtins__中.如果在模块的全局命名空间中声明名为list的变量,则解释器将永远不会在更高级别的命名空间中搜索该名称(即__builtins__).同样,假设您在模块中的函数内创建变量var,并在模块中创建另一个变量var.然后,如果在函数内部引用var,则永远不会获得全局var,因为本地命名空间中存在var – 解释器无需在其他位置搜索它.
这是一个简单的例子.
>>> 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.
所以,正如你所看到的,Python内置函数并没有什么特别之处.而你的案例仅仅是普遍规则的一个例子.您最好使用IDE(例如PyCharm的免费版本或带有Python插件的Atom)来突出显示名称阴影以避免此类错误.
您可能想知道什么是“可调用”,在这种情况下,您可以阅读以下帖子:https://stackoverflow.com/a/111255/3846213.list,是一个类,可以调用.调用类会触发实例构造和初始化.实例也可以是可调用的,但列表实例不是.如果您对类和实例之间的区别更加困惑,那么您可能希望阅读the documentation(非常方便,同一页面涵盖命名空间和范围).
如果您想了解更多有关内置组件的信息,请阅读Christian Dean的答案.
附:
启动交互式Python会话时,您将创建一个临时模块.
转载注明原文:TypeError:’list’对象在python中不可调用 - 乐贴网