Concise Python tutorial --- 8. Module
This section describes how to use functions to reuse code blocks. If you have defined a bunch of functions and want to reuse them in other programs, what should you do?
In python, you can use modules to achieve this requirement. The module is actually a file that contains a lot of functions. This file must be suffixed with. py to indicate that it is a python module.
Python also defines some standard modules. For example, SYS module.
Import sys;
Print "SYS. Path =", SYS. path;
Note that the preceding import sys statement declares that the current program has imported the SYS module. If the program uses a Chinese medicine module, you must use the Import Statement to import a module.
In addition, the file of the imported module must exist in the path included in SYS. Path.
Compiled Python source file (. PyC file)
The compiled Python source file can improve the speed of importing the file. It should be noted that this compiled file is an intermediate form and has no direct relationship with a specific platform.
From .. Import Statement
You can see the example of using the variable in the module: SYS. Path. What if you want to directly use the PATH variable but do not want to write the SYS. prefix?
You can use the from sys import path statement to replace the import sys statement.
From sys import path;
Print "SYS. Path =", path;
Module _ name __
Each module has a name. In a program, you can use the _ name _ attribute to obtain the module name.
Define your own modules
Defining a module is very simple. In fact, you have defined your own module. After you write and save a legitimate Python program in a XXX. py file, you have defined a module of your own.
For example, create a file mymodule. py with the following content:
Def func ():
Print 'hello ';
Now you can call the func () function in this module in another place:
Import mymodule;
Mymodule. func ();
From the above we can see that the name of a module is actually the name of the file where the module is located (excluding the. py suffix ).
Dir (modulename) Function
You can use the Dir () function to view the list of identifiers defined in a module.
For example, to view the list of identifiers defined in the module mymodule. py:
Import mymodule;
Dir (mymodule );