使用 __init__.py [英] using __init__.py

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

问题描述

我很难理解我的项目中 python __init__.py 文件的使用场景或设计目标.

I am having difficulty understanding the usage scenarios or design goals of python's __init__.py files in my projects.

假设我有包含以下文件的模型"目录(称为包)

Assume that I have 'model' directory (refers as a package) which contains the following files

  1. __init__.py
  2. meta.py
  3. solrmodel.py
  4. mongomodel.py
  5. samodel.py

我发现了两种使用 __init__.py 的方法:

I found two ways of using __init__.py:

  1. 我有一个共同的定义,需要在solrmodel.pymongomodel.pysamodel.py 中使用.我可以使用 __init__.py 作为所有 *model.py 类的基本/通用定义吗?这意味着我必须导入 model/__init__.py.

  1. I have common a definition which needs to be used in solrmodel.py, mongomodel.py, samodel.py. Can I use __init__.py as a base/common definition for all the *model.py classes? This means that I have to import model/__init__.py.

或者,__init__.py 应该自己导入 solrmodel.py、mongomodel.py、samodel.py 的定义,它允许像这样轻松导入类或函数:

Or, the __init__.py shall have imported definitions of solrmodel.py, mongomodel.py, samodel.py in its own and it allows the easy import of classes or function like this:

# file: __init__.py

from mongomodel import *
from solrmodel import *
from samodel import *

(我知道不推荐使用 import *,我只是将其用作约定)

(I am aware that import * is not recommended and I just used it as a convention)

我无法在上述两种情况之间做出决定.__init__.py 有没有更多的使用场景,能解释一下用法吗?

I could not decide between above two scenarios. Are there more usage scenarios for __init__.py and can you explain the usage?

推荐答案

我写的绝大多数 __init__.py 文件都是空的,因为很多包没有任何东西要初始化.

The vast majority of the __init__.py files I write are empty, because many packages don't have anything to initialize.

我可能想要初始化的一个示例是在包加载时我想一劳永逸地读取一堆数据(例如来自文件、数据库或网络)——在这种情况下,它是 将该读数放在包的 __init__.py 中的私有函数中要好得多,而不是有一个单独的初始化模块"并从每个实际模块中冗余导入该模块包(无用的重复和容易出错:这显然是依赖语言保证包的 __init__.py is 在包中的任何模块之前加载一次的情况显然更 Pythonic!).

One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's __init__.py rather than have a separate "initialization module" and redundantly import that module from every single real module in the package (uselessly repetitive and error-prone: that's obviously a case in which relying on the language's guarantee that the package's __init__.py is loaded once before any module in the package is obviously much more Pythonic!).

对于其他具体和权威的意见表达,请查看作为 Python 标准库一部分的各种包所采用的不同方法.

For other concrete and authoritative expressions of opinion, look at the different approaches taken in the various packages that are part of Python's standard library.

这篇关于使用 __init__.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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