During the creation of the Python package, the IDE creates a __init__.py file in the package root directory, which is empty by default. The directory structure is as follows:
The package tree structure under Pycharm:
The directory structure in the Finder:
As you can see from the directory in the Finder, each package is actually a directory, so how does the IDE recognize it as a package? Yes, the first function of __init__.py is the package 's identity , which, if not, is not considered to be a catalog.
The packages and modules in Python are imported in two ways: precise import and fuzzy import:
Precise import:
from Import Pack1class Import Root.Pack1.Pack1Class
Fuzzy import:
from Import *
The modules in the fuzzy import are defined by __all__, and another function of __init__.py is to define the __all__ in the package, which is used to blur the import , such as __init__.py:
__all__ = ["pack1class","pack1class1"]
Called Outside the package:
from Import *= Pack1class.pack1_aa ("Alvin") A.printname ()
__init__.py is first a python file, and all can also be used to write Python modules , but it is not recommended to do so, try to ensure that __init__.py is light enough:
__init__.py:
__all__= ["Pack1class","Pack1class1","Init_aa"]class init_aa:def __init__(self,name): Self.name=namedefgreeting (self):Print("Hello", Self.name)
Called in the test:
from Import *= Init_aa ("test") b.greeting ()
Summarize:
As can be seen from the above example, the main function of __init__.py is:
1. The identity of the package in Python cannot be deleted
2. Define __all__ for fuzzy import
3. Writing Python code (not recommended to write Python modules in __init__, you can create additional modules in the package to write, as far as possible to ensure __init__.py simple)
__init__.py function in Python package