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

查看:79
本文介绍了使用__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
  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中的私有函数中,而不是使用单独的初始化模块",并从包中的每个真实模块中冗余地导入该模块(无用的重复和错误) -prone:这显然是一种情况,其中依赖于该语言的保证,即在包中的任何模块之前,首先将包的__init__.py 加载一次,显然是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天全站免登陆