Python package and module instance, Python module instance

Source: Internet
Author: User

Python package and module instance, Python module instance

I. instances and results

1) instance structure and specific files:

Copy codeThe Code is as follows:
PyPackage
│ PyCommonM. py
│ _ Init _. py

─ ── P1Package
│ P1M. py
│ P1MC. py
│ _ Init _. py

2017-p2
P2.py
P2M. py

2) PyCommonM. py

Copy codeThe Code is as follows:
Def PyCommonMF (): print "PyCommonMF"

3) P1M. py:

Copy codeThe Code is as follows:
Def P1MF (): print 'p1mf'

4) P1MC. py:

Copy codeThe Code is as follows:
Class P1MC ():
@ Staticmethod
Def p1olap (): print 'p1w'

5) P2M. py:

Copy codeThe Code is as follows:
Def P2MF (): print 'p2mf'

6) P2.py:

Copy codeThe Code is as follows:
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. p1olap ()
PyCommonM. PyCommonMF ()

7) Running p2.py:

Copy codeThe Code is as follows:
P2F
P2MF
P1MF
P1olap
PyCommonMF

Ii. Explanation

* A py file is a module, such as module: PyCommonM. py, P2M. py, P1MC. py, and P1M. py.
* The folder containing _ init _. py is a package, for example, package: PyPackage and p1Package.
* You can directly use import to reference other modules in the same directory, for example, import P2M in p2.py.
* Use from import to reference the modules belonging to a certain package in other directories, for example, from PyPackage import PyCommonM and from PyPackage. p1Package import P1M in py. py.
* Use from import to reference classes in a module, for example, from PyPackage. p1Package. P1MC import P1MC.

Note that the directory where the package is located must be in the pythonpath environment variable.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.