You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中用import as重命名模块后为何出现ModuleNotFoundError?

解决ModuleNotFoundError: No module named 'maths'的问题

错误原因

  • import math as maths只是给Python标准库的math模块创建了一个别名maths,这个别名仅在当前代码的局部命名空间中生效,系统中并不存在一个真正名为maths的模块。
  • 执行from maths import factorial时,Python会在系统模块搜索路径中查找名为maths的模块,找不到就会抛出ModuleNotFoundError。

解决办法

  • 方法一:通过别名直接调用函数
    既然已经给math起了别名maths,直接通过别名访问函数即可:

    import math as maths
    # 使用别名调用阶乘函数
    print(maths.factorial(5))
    
  • 方法二:直接从原模块导入目标函数
    跳过别名,直接从标准库math模块导入factorial:

    from math import factorial
    print(factorial(5))
    
  • 方法三:保留别名同时导入函数(不推荐,冗余)
    如果一定要保留别名又用from...import语法,需要写原模块名:

    import math as maths
    from math import factorial
    print(factorial(5))
    

内容的提问来源于stack exchange,提问作者peedurrr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 05:24:51