Python:如何从__init__.py文件导入? [英] Python: How to import from an __init__.py file?
问题描述
我正在使用 Flask Framework 构建一个网站,其中我有一个文件夹,其中我有一些python文件和一个 __ init __。py
脚本(我想你会称这个文件夹为一个模块)。在 init .py文件中,我有一行说:
db = Database(app )
我现在要用 db
在这个文件夹中的一个不同的脚本。通常情况下,我会使用__init__ import db 中的来做到这一点,但这似乎不正确,更不用说pythonic了。此外,因为它在
__ init __。py
文件中,所以我想它应该以某种方式被初始化为整个文件夹/模块。
有人知道如何从 __ init __。py中使用
db
c $ c>文件?所有的提示都是值得欢迎的!
from。 import db
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)
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.
Does anybody know how I can use db
from the __init__.py
file? All tips are welcome!
Try relative imports
from . import db
这篇关于Python:如何从__init__.py文件导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!