Python interview questions twenty-eight (what does the __init__.py file in the package do?)

The most commonly used function of init .py file is to identify a folder as a python package.

Another function of the init .py file is to define the content to be imported during fuzzy import.

When we use an import statement like from package import *, we are using fuzzy import. At this time, the package writer can define all in the __init__.py file to limit the content of fuzzy import.

This can avoid exposing some methods or variables that are only used in the package to the user.

init .py can also simplify the import process, such as:

The models file in Django sometimes has many tables, and each table has many attributes and methods, which makes the models file very bloated.

So we will create a models package. In this package, each table will be saved with a py file, but this will cause some trouble when importing.

Now suppose we have a User table. According to our method above, we have a models folder with a User.py file in it. This file holds the classes of our User table.

In this way, when we import the User class in other files, the import statement is from app.models.User import User, but we are more accustomed to the original writing from app.models import User.

Then we can in the models in the init import User class .py file, so that we can use to import the original wording of the User class.

# models.__init__.py
from .User import User
Published 56 original articles · praised 0 · visits 1260

Guess you like

Origin blog.csdn.net/weixin520520/article/details/105488848