Python:如何从__init__.py文件导入? [英] Python: How to import from an __init__.py file?

查看:273
本文介绍了Python:如何从__init__.py文件导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Flask Framework 构建一个网站,其中我有一个文件夹,其中我有一些python文件和一个 __ init __。py 脚本(我想你会称这个文件夹为一个模块)。在 init .py文件中,我有一行说:

  db = Database(app )

我现在要用 db 在这个文件夹中的一个不同的脚本。通常情况下,我会使用__init__ import db 中的来做到这一点,但这似乎不正确,更不用说pythonic了。此外,因为它在 __ init __。py 文件中,所以我想它应该以某种方式被初始化为整个文件夹/模块。



有人知道如何从 __ init __。py中使用 db c $ c>文件?所有的提示都是值得欢迎的!

modules.html#intra-package-referencesrel =noreferrer>相对导入

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆