Skip to main content
 首页 » 编程设计

python之调用需要来自另一个文件的库的 Python 函数

2024年12月31日8haluo1

我有一个名为“custom_functions.py”的脚本,其中包含我为简化工作而编写的函数。每个自定义函数调用不同的库。 “custom_functions.py”看起来像这样:

# This is custom_functions.py 
import pandas as pd 
import numpy as np 
 
def create_df(): 
   return pd.DataFrame({'a': [1, 2, 3]}) 
 
def create_array(): 
   return np.array([1, 2, 3]) 

在过去的几个月里,随着我向 custom_functions.py 添加函数,我需要导入越来越多的库,以便能够将脚本调用到另一个文件(我们称之为“main.py” ”)。当我最终只需要一个函数时,加载所有函数的库似乎效率低下/不必要。

有没有办法只调用例如create_array 而无需加载 create_df 所需的库?这将是理想的,例如,如果我可以删除 custom_functions.py 中的所有库调用,并且在我从 custom_functions.py 中调用特定函数之前只在 main.py 中导入必要的库,例如:

# This is the proposed custom_functions.py 
def create_df(): 
   return pd.DataFrame({'a': [1, 2, 3]}) 
 
def create_array(): 
   return np.array([1, 2, 3]) 

和

# This is the proposed main.py 
import numpy as np 
from custom_functions import create_array 

上面的代码抛出一个错误(NameError: name "np"is not defined)。将 custom_functions.py 分解为单独的脚本并在每次将 custom_functions 加载到 main.py 时只加载所有相关库的唯一解决方案是什么?

如果有用,我在 Windows 10 机器上使用 Python 3.6.5 和 Anaconda。

感谢您的帮助!

请您参考如下方法:

正确的方法是将其拆分成不同的文件。

如果您真的不想这样做,您可以将任何导入放入函数中。这样做的缺点是每次调用函数时,模块都会再次导入,而不是只导入一次。如果您这样做,请尽可能绝对具体。

def create_array(): 
    from numpy import array 
    return array([1, 2, 3])