Skip to main content
 首页 » 编程设计

python之为什么这是类型错误而不是语法错误

2025年05月04日13lvdongjie

为什么会有代码

print("Average =" (sum/count)) 

产生类型错误而不是语法错误,因为缺少逗号?

谢谢。

请您参考如下方法:

Python 将 () 视为函数调用;字符串不可调用,导致 TypeError:

>>> "somestring"(42) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: 'str' object is not callable 

在 Python 中,一切 都是对象;函数也是对象,任何对象都可以实现 __call__ 方法,使每个对象都可以调用。 Python 直到运行时才知道字符串对象不可调用,因此这不是语法错误。