子模块 __init__.py 未传递给脚本

Submodule __init__.py is not passed to scripts

我的文件夹结构定义如下:

\test
    main.py
    \module
        __init__.py
        foo.py

main.py 包含:

from module.foo import bar
bar()

__init__.py 包含:

HELLO = "hello"

foo.py 包含:

def bar():
    print(HELLO)

当我在命令行 运行 中 python main.py 我得到错误:

NameError: name 'HELLO' is not defined

我不明白为什么 __init__.py 不将 HELLO 变量传递给 foo.py

在foo.py中添加

from . import HELLO

因此变量 HELLO 被导入。

变量 HELLO 的完全限定名称是 module.HELLO。这意味着 HELLO 在包 module.

中定义

要定义这个常量,您需要导入您的模块。

例如:

foo.py 中,您必须:

from module import HELLO

def bar():
    print(HELLO)