将我的代码拆分为 Python 中的多个文件 3

Splitting my code into multiple files in Python 3

我希望将我的代码拆分成多个文件 Python 3.

我有以下文件:

/hello
    __init__.py
    first.py
    second.py

其中上述文件的内容为:

first.py

from hello.second import say_hello

say_hello()

second.py

def say_hello():
    print("Hello World!")

但是当我运行:

python3 first.py

hello 目录中时出现以下错误:

Traceback (most recent call last):
  File "first.py", line 1, in <module>
    from hello.second import say_hello
ImportError: No module named 'hello'

换出

from hello.second import say_hello

对于

from second import say_hello

您的默认 Python 路径将包括您的当前目录,因此直接从 second 导入即可。为此,您甚至不需要 __init__.py 文件。你,但是,如果你想从包外导入,需要__init__.py文件:

$ python3
>>> from hello.second import say_hello
>>> # Works ok!

你不应该 运行 python3 在 hello 目录中。

你应该 运行 它在 hello 目录之外并且 运行

python3
>>> import hello.first

顺便说一下,Python 中不再需要 __init__.py 3. 参见 PEP 420

不能从当前目录导入包。

可以使用 if/else 测试或 try/except 处理程序使其工作,但它的工作量超出了它的价值。

只是 cd .. 所以你不在包的目录中,它会正常工作。