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

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

问题描述

我正在寻找我将在 __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 文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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