如何在同一目录或子目录中导入类? [英] How to import the class within the same directory or sub directory?
问题描述
我有一个存储所有 .py 文件的目录.
I have a directory that stores all the .py files.
bin/
main.py
user.py # where class User resides
dir.py # where class Dir resides
我想在 main.py 中使用 user.py 和 dir.py 中的类.
如何将这些 Python 类导入 main.py?
此外,如果 user.py 位于子目录中,我如何导入 User
类?
I want to use classes from user.py and dir.py in main.py.
How can I import these Python classes into main.py?
Furthermore, how can I import class User
if user.py is in a sub directory?
bin/
dir.py
main.py
usr/
user.py
推荐答案
Python 2
在与文件相同的目录中创建一个名为 __init__.py
的空文件.这将向 Python 表明可以从此目录导入".
Python 2
Make an empty file called __init__.py
in the same directory as the files. That will signify to Python that it's "ok to import from this directory".
那就做……
from user import User
from dir import Dir
如果文件位于子目录中,同样适用 - 在子目录中也放置一个 __init__.py
,然后使用带点符号的常规导入语句.对于每一级目录,都需要添加到导入路径中.
The same holds true if the files are in a subdirectory - put an __init__.py
in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.
bin/
main.py
classes/
user.py
dir.py
所以如果目录被命名为classes",那么你会这样做:
So if the directory was named "classes", then you'd do this:
from classes.user import User
from classes.dir import Dir
Python 3
与之前相同,但在模块名称前加上 .
如果不使用子目录:
from .user import User
from .dir import Dir
这篇关于如何在同一目录或子目录中导入类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!