python - 为什么我的 __init__.py 在模块中不起作用?

标签 python python-3.x

我试图将“project_root”添加到__init__.py中,所有模块都可以使用它,但它不起作用。

环境:Python 3.7.0 MACOS MOJAVE

文件结构

·
├── __init__.py
└── a.py

__init__.py文件中的代码:

import sys

project_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(project_root)

在另一个文件中

print(project_root)

如果我在同一目录中运行python a.py,或者在该目录之外运行python a.py,错误如下:

Traceback (most recent call last):
  File "a.py", line 1, in <module>
    print(project_root)
NameError: name 'project_root' is not defined

我的问题是为什么它不起作用以及如何修复它。 另外一个问题是,如果想为同一个包中的其他模块共享一些变量,该怎么做?

最佳答案

让我们尝试通过例子来理解。

代码及目录说明:

假设我们有以下目录和文件结构:

dir_1
    ├── __init__.py
    └── a.py
b.py

__init__.py 包含:

import sys,os

# Just to make things clear
print("Print statement from init")

project_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(project_root)

a.py 包含:

def func():
    print("func from a.py")

让我们开始导入东西:

假设您首先在 b.py 中包含以下代码:

from dir_1.a import func

func()

执行上述命令将得到以下输出:

Print statement from init
func from a.py

因此,从上面我们可以了解到,__init__.py 中的 print 语句正在执行。现在,让我们在 b.py 中添加 print(project_root):

from dir_1.a import func

func()
print(project_root)

执行上述命令将导致错误:

...
NameError: name 'project_root' is not defined

发生这种情况是因为我们不必从 __init__.py 导入 print 语句,它只是被执行。但变量的情况并非如此。

让我们尝试导入变量并看看会发生什么:

from dir_1.a import func
from dir_1 import project_root

func()
print(project_root)

执行上述文件将给出以下输出:

Print statement from init
func from a.py
/home/user/some/directory/name/dir_1

长话短说,您需要导入__init__.py中定义的变量 或其他任何地方以便使用它。

希望这有帮助:)

关于python - 为什么我的 __init__.py 在模块中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501786/

相关文章:

python - 获取文章->产品关系的最低价目表

python - 多个目录的错误处理

python - SQLAlchemy:在回滚无效事务之前无法重新连接

python - 外壳脚本: time and python into a file

python - 合并具有相同日期的行并在 Pandas 中添加计数器列

python - Django DetailView 动态模型

python - 导航到没有用户名的文件

python - 使用 Webargs Flaskparser 验证 URL 路径和查询参数中的变量参数

Python类: How to check whether an attribute is defined inside __init__ or outside __init__

android - 使用 Arduino 和 pySerial 进行串行数据记录