Introduction to modules for advanced python tutorials

  • 2020-04-02 14:03:07
  • OfStack

We've seen functions and objects before. Essentially, they are designed to better organize existing programs for easy reuse.

Modules serve the same purpose. In Python, a.py file makes up a module. With modules, you can call programs in other files.

The introduction of the module

Let's first write a first.py file, which is as follows:


def laugh():
    print 'HaHaHaHa'

Write a second. Py and introduce the program in first:


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 imported module can be invoked by means of a module.object. In the above example, first is the module we introduced, and laugh() is the object we introduced.

There are other ways of introducing it in Python


import a as b             # The introduction of the module a And will module a rename b from a import function1   # From the module a The introduction of function1 Object. call a In the object, we do not need to explain the module, that is, direct use function1 Rather than a.function1 . from a import *           # From the module a All objects are introduced in. call a In the object, we do not need to explain the module, that is, directly use the object, not a. Object.

These methods of reference, can be easy to write later procedures.

The search path

Python searches for the module it is looking for in the following path:

The folder where the program resides
Standard library installation path
The path contained in the operating system environment variable PYTHONPATH

If you have a custom module, or a downloaded module, you can place it in the appropriate path so that Python can find it.

Module package

You can put modules with similar functionality in the same folder (such as this_dir) to form a module package. through


import this_dir.module

Introduce the module module in the this_dir folder.

This folder must contain a file with s/p. Py, reminding Python that the folder is a module package. S/p can be an empty file.

conclusion

The import module

The module. The object

Just set py


Related articles: