Python:如何从 __init__.py 文件导入? [英] Python: How to import from an __init__.py file?
问题描述
我正在使用 Flask 框架 构建一个网站,其中有一个文件夹,其中包含我有一些 python 文件和一个 __init__.py
脚本(我猜你会称这个文件夹为模块?).在 init.py 文件中,我有一行说:
I'm building a website using the Flask Framework, in which I've got a folder in which I have some python files and an __init__.py
script (I guess you would call this folder a module?). In the init.py file I've got a line saying:
db = Database(app)
我现在想在此文件夹中的不同脚本中使用 db
.通常我会使用 from __init__ import db
来做到这一点,但这似乎不正确,更不用说pythonic了.此外,由于它在 __init__.py
文件中,我想它应该以某种方式为整个文件夹/模块初始化.
I now want to use db
in a different script which is in this folder. Normally I would do this using from __init__ import db
, but that just doesn't seem right to do, let alone pythonic. Furthermore, since it is in the __init__.py
file, I suppose it should somehow be initialised for the whole folder/module.
有人知道我如何使用 __init__.py
文件中的 db
吗?欢迎所有提示!
Does anybody know how I can use db
from the __init__.py
file? All tips are welcome!
推荐答案
尝试 相对导入
from . import db
这篇关于Python:如何从 __init__.py 文件导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!