1. Simple situation
There are two main ways to import packages and modules in Python:
(1) Import Package.module
(2) from package Import module
After the module is imported into the current program, the corresponding properties in module attr are used in the following ways:
(1) package.module.attr
(2) module.attr
This allows you to summarize the rule of member references in a module:
Import imported packages, use the ' absolute path ' when using the specific members in the package, and write the member reference path from the top-level package name;
From-import imported packages that use ' relative paths ' when using specific members of the package, starting with the module after import from the from-import structure to write the member reference path; 2. Complex Scenarios
When a package contains a child package, and considering the role of the __init__.py file, the package, the import of the module, and the use of the members are more complex and confusing, for example, Python programming with the following package structure:
pkg/
__init__.py
subpkg_a/
__init__.py
mod_a.py
mod_a1.py mod_a2.py subpkg_b/
__init__.py
mod_b.py
__init__.py file Explanation: Each package has a __init__.py file, this is a package initialization module, import the package in essence is to import the module defined in the file, you can do some initialization work in the file, can also be empty files.
According to the package structure mentioned above, if you want to use the functions in Mod_a and MOD_A1 in mod_b.py (note that the functions are referenced differently in various import modes), there are several ways to do this:
Write import pkg.subPkg_a.mod_a, import pkg.subPkg_a.mod_a1, or from pkg.subpkg_a import mod_a, from pkg.subpkg_a in mod_b.py files Import MOD_A1
The import pkg.subPkg_a.mod_a and import pkg.subPkg_a.mod_a1 are written in the corresponding __init__.py file of the subpkg_a, so you can use imports in the mod_b.py file. The pkg.subpkg_a or from pkg.subpkg_a import * is imported into mod_a and Mod_b, as shown in the following figure.
When a package contains more than one module, you can also use the __all__ variable to store a list of import modules in __init__.py, as shown in the following figure.
Note: Because MOD_A2 is not included in the __ALL__ variable list, members in MOD_A2 cannot be used in mod_b.