Python basics === package import and _ init _. py introduction, python _ init _. py
Call the same level directory:
-Src
|-Mod. py
|-Test. py
If you import the module mod in the test. py program, you can directly use
import mod
Or
from mod import *
Call the modules in the subdirectory:
-Src
|-Mod. py
|-Lib
|-Mod2.py
|-Test. py
from lib.mod2 import *
Or
import lib.mod2
Call the files in the upper-level directory
The directory structure is as follows:
-Src
|-Mod. py
|-Lib
|-Mod2.py
|-Sub
|-Test2.py
import sys
sys.path.append('C:\\test\\A\\C')
import mod
import lib.mod2
_ Init _. py
In each package of the python module, There Is A _ init __. the py file (which defines the attributes and methods of the package) is followed by some module files and subdirectories. If the subdirectory also contains _ init __. py, It is the sub-package of this package. When you import a package as a module (for example, importing dom from xml), you actually import its _ init _. py file.
A package is a directory with a special file _ init _. py. The _ init _. py file defines the attributes and methods of the package. In fact, it can not be defined; it can be just an empty file, but it must exist. If _ init _. py does not exist, this directory is just a directory, rather than a package, and cannot be imported or contain other modules and nested packages.
Another important variable in _ init _. py is called _ all __.
If the directory is as follows:
-Src
|-Mod. py
|-Lib
|-Mod2.py
|-Mod3.py
|-Sub
|-Mod3.py
We sometimes make a trick to "import all", that is:
from lib import *
In this case, import the sub-modules and sub-packages registered in the _ init _. py file _ all _ list to the current scope. For example:
# File _ init _. py
__all__ = ["mod2", "mod3", "sub"]
Summary:
To download py files from other paths, add them to sys. path before importing them.
_ Init _. py:
- The ID of the package. The package cannot be deleted.
- Define _ all __in the package for Fuzzy import.
- Compile Python code (it is not recommended to write the python module in _ init _. You can create another module in the package to write it. Make sure that _ init _. py is simple)