导入自定义函数

吕克斯潘

设置

我有2个.py在2个不同地点,即文件'mypath/folder_A''mypath/folder_B'

文件A.py包含 2 个需要导入到B.py.

A.py 看起来像,

def test_function_1(x):
    y = x + 1
    return y

def test_function_2(x):
    y = x + 2
    return y

B.py模样,

os.chdir('/mypath/folder_A')
import A

test_function_1(1)
test_function_2(1)

问题

当我跑步时B.py,我得到了NameError: name 'test_function_1' is not defined

但如果我适应B.py了,

from A import test_function_1, test_function_2

并运行B.py,它的工作原理。


问题

如何将函数从A.pyinto 导入B.py而不必全部命名?

即有from A import everything吗?

合酶

你在找什么:

from A import *

你也可以这样做:

import A

A.test_function_1(1)

或者:

import A as a

a.test_function_1(1)

此外,库通常从 $PYTHONPATH

所以如果你在你的.bashrc:

export PYTHONPATH="$PYTHONPATH:/mypath/folder_A/"

.bashrc在 GNU/Linux 上编辑

gedit $HOME/.bashrc

然后就不需要你的了os.chdir(),你可以直接从任何地方导入。

B.py会看起来像:

from A import *

test_function_1(1)
test_function_2(1)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章