Package and module instances in Python
- 2020-04-02 14:24:04
- OfStack
Examples and results
1) structure of the instance and specific files:
PyPackage
│ PyCommonM.py
│ __init__.py
│
├ ─ p1Package
│ P1M.py
│ P1MC.py
│ __init__.py
│
└ ─ p2
P2.py
P2M.py
2) PyCommonM. Py
def PyCommonMF(): print "PyCommonMF"
3) P1M. Py:
def P1MF(): print 'P1MF'
4) P1MC. Py:
class P1MC():
@staticmethod
def P1MCF(): print 'P1MCF'
5) P2M. Py:
def P2MF(): print 'P2MF'
6) P2. Py:
import P2M
from PyPackage import PyCommonM
from PyPackage.p1Package import P1M
from PyPackage.p1Package.P1MC import P1MC
def P2F():
print 'P2F'
if __name__ == '__main__':
P2F()
P2M.P2MF()
P1M.P1MF()
P1MC.P1MCF()
PyCommonM.PyCommonMF()
7) results of running p2.py:
P2F
P2MF
P1MF
P1MCF
PyCommonMF
Second, the interpretation
*
A py file is a module, such as module: pycommonm.py, p2m.py, p1mc.py, p1m.py.
*
The folder containing s/s. Py is one package, e.g. Package: PyPackage, p1Package.
*
You can use import directly to refer to other modules in the same directory, such as import P2M in p2.py.
*
From import refers to modules in other directories belonging to a package, such as from PyPackage import PyCommonM and from pypackage. p1Package import P1M in py.py.
*
From import to refer to a class in a module, such as from pypackage.p1package.p1mc import P1MC
Note that the directory where the package resides must be in the pythonpath environment variable.