如何在Python中调用其他目录中的类

0 投票
3 回答
6836 浏览
提问于 2025-04-17 13:57

我有一个主要的执行文件(F),我想在里面使用其他 Python 类中的一些服务(S)。文件夹结构是:

root/a/my file to execute -- (F)
root/b/python class I would like to use -- (S)

我该如何在我的文件(F)中调用这个请求的 Python 类(S)呢?

谢谢。

3 个回答

0

在你想要包含的目录里创建一个 __init__.py 文件。

假设我们有两个目录,一个叫 src,另一个叫 utils

如果你在 src 目录里有一个 Main.py 文件,并且你想在 utils 目录里的 Connections.py 文件中使用一个叫 Network 的类,那么你可以这样做。

请注意,任何你创建的包含 *.py 文件的文件夹都适用这个规则。例如,我们可以有 a, b, c 这样的文件夹,你只需写 from a.b.c import Connections,或者根据你的文件名来调整...

1)utils 目录里创建一个 __init__.py 文件(这个文件可以是空的),然后在你的 Main.py 文件中这样做。

from utils import Connections

my_instance = Connections.Network()

#Then use the instance of that class as so.
my_instance.whateverMethodHere()

目录结构看起来是这样的:

root dir
  - src 
    -__init__.py
    - Main.py

  - utils
    -__init__.py
    - Connections.py

想了解更多细节,可以查看 Python 的文档,里面有更深入的内容。 http://docs.python.org/tutorial/modules.html#packages

根据上面的链接,关于 Python 包和为什么我们使用 __init__.py 的更多信息:

当导入包时,Python 会在 sys.path 中查找目录,寻找包的子目录。

init.py 文件是必需的,它让 Python 将这些目录视为包含包的目录;这样做是为了防止一些常见名称的目录,比如 string,意外地隐藏后面模块搜索路径中有效的模块。在最简单的情况下,init.py 可以只是一个空文件,但它也可以执行包的初始化代码或设置后面会提到的 all 变量。

1

举个例子,下面是你当前的文件夹结构:

A folder:
  file a.py
  file b.py
B folder:
  file c.py
  file d.py

在 c.py 文件中,你想把 a.py 导入到你的宏里。你可以这样做:

import os
# insert 1, 2, 3... but not 0, 0 is your working directory
sys.path.insert(1, "Folder A 's absolute path")
# Here, you can import module A directly    
import a
2

这可能听起来很简单,但其他回答没有提到确保模块 b 在你的 sys.path 中。因此,假设问题中的文件夹结构是这样的,并且假设目录 b 里有一个叫 __init__.py 的文件,和模块 s.py 在一起,那么你需要这样做:

# Add the b directory to your sys.path

import sys, os
parent_dir = os.getcwd() # find the path to module a
# Then go up one level to the common parent directory
path = os.path.dirname(parent_dir)
# Add the parent to sys.pah
sys.path.append(path)

# Now you can import anything from b.s
from b.s import anything
...

撰写回答