This article mainly introduces the module of the python advanced tutorial. This article describes the basic knowledge, reference methods, search paths, module packages, and other knowledge, for more information, see functions and objects. Essentially, they all aim to better organize existing programs for reuse.
The module is also for the same purpose. In Python, A. py file forms a module. Through the module, you can call programs in other files.
Introduction module
First, write a first. py file with the following content:
The Code is as follows:
Def laugh ():
Print 'hahahahaha'
Write another second. py and introduce the program in first:
The Code is as follows:
Import first
For I in range (10 ):
First. laugh ()
In second. py, we use the laugh () function defined in first. py.
After a module is introduced, an object in the introduced module can be called through the module. Object method. In the above example, the first is the introduced module, and laugh () is the object we introduce.
There are other import methods in Python.
The Code is as follows:
Import a as B # introduce module a and rename module a to module B
From a import function1 # introduce the function1 object from module. When calling an object in a, we do not need to describe the module, that is, directly use function1 instead of a. function1.
From a import * # introduce all objects from module. When calling an object in a, we do not need to describe the module, that is, directly use an object instead of a. object.
These Reference Methods facilitate subsequent program writing.
Search Path
Python will search for the module it is looking for in the following path:
Folder where the program is located
Standard Library installation path
Path included in the operating system environment variable PYTHONPATH
If you have a custom module or a downloaded module, you can put it in the corresponding path as needed so that Python can find it.
Module package
You can place modules with similar functions in the same folder (such as this_dir) to form a module package. Pass
The Code is as follows:
Import this_dir.module
Introduce the module in the this_dir folder.
This folder must contain a _ init _. py file to remind Python that the folder is a module package. _ Init _. py can be an empty file.
Summary
Import module
Module. object
_ Init _. py