Python:从带有所需模块的 .py 文件导入函数

mma*_*123 3 python module function

我正在尝试做一些相当简单的事情。我想从 .py 文件导入一个函数,但使用在我的主脚本中导入的模块。例如存储以下函数

./文件/罪人.py

def sinner(x):
  y = mt.sin(x)
  return y
Run Code Online (Sandbox Code Playgroud)

然后我想使用数学作为 mt 运行罪人

from sinner import sinner
import math as mt
sinner(10)
Run Code Online (Sandbox Code Playgroud)

这并不奇怪会引发错误

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-50006877ce3e> in <module>()
      2 import math as mt
      3 
----> 4 sinner(10)

/media/ssd/Lodging_Classifier/sinner.py in sinner(x)
      1 import math as mt
----> 2 
      3 def sinner(x):
      4   y = mt.sin(x)
      5   return y

NameError: global name 'mt' is not defined
Run Code Online (Sandbox Code Playgroud)

我知道如何在 R 中处理这个问题,但在 Python 中不知道。我错过了什么?

Tgs*_*591 5

sinner.py命名空间中不存在 math 模块。与 R 不同,导入的模块或包不跨越全局命名空间。您需要mathsinner.py文件中导入:

import math as mt

def sinner(x):
  y = mt.sin(x)
  return y
Run Code Online (Sandbox Code Playgroud)

或者(我真的不知道你为什么要这样做),你可以将模块作为参数传递给sinner函数:

def sinner(mt, x):
  y = mt.sin(x)
  return y
Run Code Online (Sandbox Code Playgroud)

然后你可以传递实现该sin功能的不同模块:

from .sinner import sinner
import math as mt
import numpy as np
sinner(mt, 10)
sinner(np, 10)
Run Code Online (Sandbox Code Playgroud)