我为什么要在__init__.py文件中放入python代码 [英] why would I put python code in __init__.py files

查看:134
本文介绍了我为什么要在__init__.py文件中放入python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找要放入__init__.py文件中的代码类型以及与此相关的最佳实践.还是一般来说是不好的做法?

I am looking for what type of code would I put in __init__.py files and what are the best practices related to this. Or, is it a bad practice in general ?

任何对解释此问题的已知文档的引用也非常感谢.

Any reference to known documents that explain this is also very much appreciated.

推荐答案

库和框架通常使用__init__.py文件中的初始化代码来巧妙地隐藏内部结构并为用户提供统一的界面.

Libraries and frameworks usually use initialization code in __init__.py files to neatly hide internal structure and provide a uniform interface to the user.

让我们以Django表单模块为例.表单模块中的各种函数和类根据它们的分类在不同的文件中定义.

Let's take the example of Django forms module. Various functions and classes in forms module are defined in different files based on their classification.

forms/
  __init__.py
  extras/
    ...
  fields.py
  forms.py
  widgets.py
  ...

现在,如果要创建表单,则必须知道每个函数在哪个文件中定义,并且用于创建联系表单的代码必须看起来像这样(不方便且丑陋).

Now if you were to create a form, you would have to know in which file each function is defined and your code to create a contact form will have to look something like this (which is incovenient and ugly).

 class CommentForm(forms.forms.Form):
    name = forms.fields.CharField() 
    url = forms.fields.URLField()
    comment = forms.fields.CharField(widget=forms.widgets.Textarea) 

相反,在Django中,您可以直接从表单名称空间引用各种窗口小部件,表单,字段等.

Instead, in Django you can just refer to various widgets, forms, fields etc. directly from the forms namespace.

from django import forms

class CommentForm(forms.Form):
    name = forms.CharField()
    url = forms.URLField()
    comment = forms.CharField(widget=forms.Textarea)

这怎么可能?为了使之成为可能,Django将以下语句添加到forms/__init__.py文件中,该文件将所有小部件,表单,字段等导入forms命名空间.

How is this possible? To make this possible, Django adds the following statement to forms/__init__.py file which import all the widgets, forms, fields etc. into the forms namespace.

from widgets import *
from fields import *
from forms import *
from models import *

如您所见,这简化了创建表单的过程,因为现在您不必担心每个函数/类的定义位置,而直接在forms命名空间中使用所有这些函数/类.这只是一个例子,但是您可以在其他框架和库中看到类似的例子.

As you can see, this simplifies your life when creating the forms because now you don't have to worry about in where each function/class is defined and just use all of these directly from forms namespace. This is just one example but you can see examples like these in other frameworks and libraries.

这篇关于我为什么要在__init__.py文件中放入python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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