本文介绍了如何从另一个模块将单个函数导入Python中的main.py?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

from someDirectory.two import ClassA

哪个适用于导入整个类,但是说我在另一个类中有一个函数 myFunction() ClassB 包含在相同的 two.py 模块中,我希望能够在我的 main.py 中使用它。

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

有没有办法可以抓住这个功能,用于我的 main.py 或其他模块,无需导入整个类或重新定义相同的函数?

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

推荐答案

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

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)

然后你可以继续做

from module import function

更新

以下主题详细介绍了如何在Windows或类Unix系统中将目录永久添加到python路径:

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

这篇关于如何从另一个模块将单个函数导入Python中的main.py?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 16:16