如何将单个函数从另一个模块导入 Python 中的 main.py?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17346950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:58:03  来源:igfitidea点击:

How to import a single function to my main.py in Python from another module?

pythonimport

提问by user2497792

In my script I have a function inside a module which I wish to be able to use in my main module to prevent redundancy. This other module (not my main, let's call it two.py) contains several classes and to import a class for use in another module one would use

在我的脚本中,我在一个模块中有一个函数,我希望能够在我的主模块中使用它来防止冗余。这个另一个模块(不是我的主要模块,我们称之为two.py)包含几个类,并导入一个类以在另一个模块中使用

from someDirectory.two import ClassA

Which works fine for importing the entire class, but say I have a function myFunction()in a different class ClassBcontained in the same two.pymodule, which I want to be able to use in my main.py.

这适用于导入整个类,但假设我在同一模块中包含myFunction()的不同类ClassB中有一个函数two.py,我希望能够在我的main.py.

Is there a way which I can "grab" that function for use in my main.pyor other modules, without having to import the entire class or redefine the same function?

有没有一种方法可以“抓取”该函数以在我的main.py模块或其他模块中使用,而无需导入整个类或重新定义相同的函数?

采纳答案by ChrisProsser

You need to make sure that the directory you wish to import code from is in your system path e.g.:

您需要确保您希望从中导入代码的目录在您的系统路径中,例如:

sys.path.insert(0, path_to_your_module_dir)

Then you can go ahead and do

然后你可以继续做

from module import function

UPDATE

更新

The following thread has details of how to permanently add the directory to your pythonpath in either Windows or Unix-like systems:

以下线程详细介绍了如何在 Windows 或类 Unix 系统中将目录永久添加到 pythonpath:

Permanently add a directory to PYTHONPATH

将目录永久添加到 PYTHONPATH