创建get_squares模块后调用报错'module' object is not callable及导入问题求助
问题解决方法
核心问题是函数代码未正确缩进,导致Python无法识别get_squares函数的存在,进而引发后续导入和调用错误。
错误原因拆解
- 直接导入模块后执行
get_squares([1,2,3])时,报错'module' object is not callable——你把模块本身当成函数调用了,而模块内实际没有可调用的目标函数(缩进错误导致函数定义不生效)。 - 尝试
from get_squares import get_squares时报错找不到函数,同样是因为缩进问题,Python未将get_squares识别为模块内的有效函数。
修复步骤
- 修正
get_squares.py的函数缩进(Python要求函数体代码必须缩进,通常为4个空格):
def get_squares(numbers): squares = [number**2 for number in numbers] print(squares)
- 现在可以正常导入并调用:
- 方式一:导入整个模块后调用函数
import get_squares get_squares.get_squares([1,2,3]) # 输出 [1,4,9] - 方式二:直接导入函数
from get_squares import get_squares get_squares([1,2,3]) # 输出 [1,4,9]
- 方式一:导入整个模块后调用函数
内容的提问来源于stack exchange,提问作者shiggyg123
相关产品推荐
相关产品推荐

