We've seen functions and objects before. In essence, they are all designed to better organize the procedures already in place to facilitate re-use.
Module is also for the same purpose. In Python, a. py file forms a module. Through the module, you can invoke programs in other files.
Introducing Modules
Let's start by writing a first.py file that reads as follows:
The code is as follows:
Def laugh ():
print ' Hahahaha '
Write a second.py and introduce the first program:
The code is as follows:
Import first
For I in range (10):
First.laugh ()
In second.py, we used the laugh () function defined in first.py.
Once the module is introduced, an object in the ingest module can be invoked by means of the module. Object. In the example above, first is the introduced module, and laugh () is the object we introduced.
There are other ways to introduce it in Python.
The code is as follows:
Import a as B # introduce module A and rename module A to B
From a import function1 # introduces the Function1 object from module A. When we call an object in a, we do not have to explain the module, which is to use function1 directly, not a.function1.
From a import * # All objects are introduced from module A. When we call an object in a, we don't have to explain the module, which is to use the object directly, not the A. Object.
These reference methods can be easily written in the following program.
Search Path
Python searches the following path for the module it wants to find:
The folder where the program resides
Installation path of the standard library
The path that the operating system environment variable Pythonpath contains
If you have a custom module, or a downloaded module, you can place the appropriate path according to the situation so that Python can find it.
Module Package
Similar modules can be placed in the same folder (for example, This_dir) to form a module package. Pass
The code is as follows:
Import This_dir.module
Introduce module modules in the This_dir folder.
The folder must contain a __init__.py file that reminds Python that the folder is a module package. __init__.py can be an empty file.
Summarize
Import Module
Module.object
__init__.py