Why do I keep getting the error "File "TypeError: 'int' object is not callable"?

Why do I keep getting the error "File "TypeError: 'int' object is not callable"?

希望有人可以帮助解释为什么我在 Python 中不断收到以下错误。

Python版本:Python3.10.4 OS: Windows 虚拟机中有 11 个

在 REPL 或 JuyterLab 中重现错误的步骤。

def minmax(items):
    return min(items), max(items)
lst = [98, 34, 78, 1, 0, -10, -19, -1]
(min, max) = minmax(lst) # **no error**
min, max = minmax(lst) # **error**. after this point I cannot call minmax without an error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in minmax
TypeError: 'int' object is not callable
'int' object is not callable

(min, max) = minmax(lst) # **error**
a, b = minmax(lst) # **error**
min, max = minmax(lst) # **error**

重启REPL或者在JypterLab重启内核即可解决问题。这给了我一个提示,这个问题可能与 Python 将变量与对象绑定有关。

请求:哪位花时间回复的也请附上你的思考过程。例如,“我以前看过这个,我知道……”或者“我阅读了 Python 文档并看到了……这让我进行了实验并发现了……”

我希望能够自己调试这些,并希望了解用于获得答案的思考过程。

到目前为止我尝试了什么? -REPL 进行实验 -Jyputer笔记本来做实验 -阅读https://careerkarma.com/blog/python-typeerror-int-object-is-not-callable/

这一行:

(min, max) = minmax(lst)

您正在将整数分配给 minmax。然后,您尝试在此处调用这些整数:

def minmax(items):
    return min(items), max(items)  # this line

在您的交互式控制台中试试这个:

>>> min([1, 0, 2])
0
>>> min = 42
>>> min([1, 0, 2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> 

Request: Whoever takes the time to respond, please also include your thought process.

每当您看到回溯:

  1. 找到它引用的行
  2. 尝试找出所有可能触发它的东西。

所以:

  1. 追溯指向这一行:
    return min(items), max(items)
  1. 回溯说:'int' object is not callable。这意味着您正在尝试调用 int 对象。您只在此行调用 minmax,因此 minmax 必须是整数。怎么可能?
  2. 您可能会注意到,稍后您在代码中分配给 minmax