Python creation Module (Chapter Fifth: modules)

Source: Internet
Author: User

The module provides a convenient way to share Python code between programs. Python provides a library of hundreds of modules that you can invoke in your footsteps or create your own modules.

This chapter describes

Internal mechanism of the research module

Create a module that contains only functions

Defining classes in a module

Extending classes through subclasses

Defining exceptions to report error status

Create a document for a module

Test module

To run a module as a program

Mounting module

5.1 Research Modules

The module is just a Python source file that can contain variables, classes, functions, and any other elements that are available in the Python script.

By using the Dir function, you can better understand the module and pass the name of a Python element (such as a module) to the Dir function, which lists all the attributes of that element. For example, to see the properties of _bulitins_, including built-in functions, classes, and variables, you can use the following statement

Dir (_builtins_)

This will get output similar to the following

For a language with many features like Python, it has very few built-in elements. You can also run the Dir function on the imported module, for example:

Using DIR helps you study the modules, including the modules you create.

5.1.1 Import Module

Import Module

You can use this syntax for Python or for modules that you create, or you can use another syntax like the following:

From module Import Item

This syntax imports only one of the required item classes or the item function.

If the module is modified, you can reload the new definition of the module using Imp.reload (module).

Import Module

Import Imp

Imp.reload (module)

Replace module with modules that you want to reload.

5.1.2 Find Module

In order to import a module, the Python interpreter first needs to find him. For a module, the Python interpreter will first find a file that becomes module.py, where module is the name of the modules passed to the import statement. When the module is found, the Python interpreter compiles a. pyc file.

The Python interpreter finds the part of the directory in the module's search path. These directories are listed in the Sys.path variable in the SYS module.

To list the location of the Python parser lookup module, you can print the value of the Sys.path variable in the Python interpreter.

5.1.3 Understanding Module

Because Python is an open source package, you can get the source code for the Python interpreter and all the modules.

First, all directories listed in the Sys.path variable find the file that ends in. py. These files are Python modules, some modules contain only functions, some contain classes and functions, for example, python3.0 parser module defines a class:

This small module consists mainly of documents that guide the user on how to use the module. This also helps to understand how to create your own modules.

5.2 Creating modules and packages

Create a module with a function

Enter the following Python code and name the file food.py

This is a module that you can then use to import the module using the Python interpreter, for example:

Case Description:

Python uses a very simple method to define a module. You can use any Python source file as a module, as shown in this simple example.

If there is a problem with food without a prefix, importing the module with another syntax can solve the problem.

5.3 Using Classes

Most modules define a collection of related functions or classes, and Python can access the data in the class by default, which violates some of the concepts of object-oriented programming, when the benefits are practical.

5.3.1 defining object-oriented programming

5.3.2 Creating a Class

Create a meal class

Each instance of the meal class holds 3 data values: Meal class name, food and drink, meal class The default name is generic meal, and so on

5.3.3 Expanding existing classes

The breakfast class expands the meal class by the definition shown below

And also

With the lunch class, you can see some of the application of setter methods.

5.4 Completing the module

After defining the classes and functions of the module, the next step is to complete the module to make it more appropriate for the Python user and Python interpreter conventions.

The completion module includes a lot of work when at least the following actions need to be done

Defining errors and exceptions for application modules

Defines the items to be exported in the module, which defines the public API for the module

Writing a document for a module

Test module

Provides a fallback function when the module executes as a program

5.4.1 Defining module-specific errors

In most cases, the exception class does not need to define any methods or initialize any data, and the exception base class provides enough.

Note: Not always, for example, an XML parsing exception might include the line number where the Duanwu occurred, and a description of the wrong thing.

5.4.2 Choose which content to export

When importing a module using from form, you can specify which item in the Import module, for example, the following statement imports angrycheexception from the meal module.

 from Meal angrycheexception

To import all public items from a module, you can use the following format:

 from Import *

* Tell the Python interpreter to import all the public methods of the module. What is a public method? As the designer of the module, you can choose to define those items as public methods that can be exported.

There are two methods of Python interpreter

If the variable _all_ is defined in the module

If the variable _all_ is not defined in the module, the interpreter imports items other than items that begin with the name underscore _. If the printit is public, and the _printit is not public.

As a best practice, you should always define _all_ in the module. This explicitly controls the items that other Python scripts can import. To do this, you can simply create a sequence of document strings, each corresponding to the name of each item you want to export from the module.

In the meal module:

Each name in this sequence is a class or function that needs to be exported from a module

It is important to select what you want to export, and when you create a module, you create an API that performs some useful functions. The APIs that are exported from the module define what the users of the module can achieve. You want the user who exported the module to be able to get all the functionality needed to do the job, but there's no need to export everything, and there might be some reasons to exclude items.

The items you might want to modify should remain private.

Modules often intentionally hide complex code (encapsulation)

5.4.3 creating a document for a module

It's important to document the module, or nobody will know what the module can do.

Browse the documentation for the module

Start the Python interpreter in interactive mode, and then like the following import and help commands:

Help is your assistant, which displays the documentation for the module.

5.4.4 Test Module

Creating Tests allows you to verify that the functionality is still valid after you modify the module

Any responsible module should contain a test function that performs the function of the module, and the test should create an instance of the class defined in the module, for example, the following method provides a test of the meal module:

Integrate the test functions into the module so that the tests are always available.

5.4.5 running the module as a program

Typically, modules should not run on their own. Other Python scripts import items from the module and use them. However, because any file that contains Python code can be thought of as a module, you can run a module.

Because you do not want the module to run itself, Python defines a convention for the module. When a module runs itself, it should perform a module test. This provides a simple way to test the module: Run the Python module as a script.

To support this convention, Python provides a simple form to detect whether a module is running as a program. Using the test function given earlier, you can use the following code to perform a test of the module:

if _name_=='_main_':     test ()

If you look at the source code of a standard Python module, you will encounter this form over and over again.

Running the module

You can run the module as a program by using the following command line:

This instance runs the module as a Python program, checking the situation using the form given earlier, knowing that the module only runs the test function, and that the output you see is the output of the test.

Note that an instance of each class defined in the module is run in the output, and the angrychefexception exception is tested.

If you follow all the guidelines for the design class described in this section, the module will meet the expectations of other Python developers. Also, the module will work better in the script. This can be seen in the actual application in the next section, which demonstrates a complete Python module.

5.5 Creating a complete module

The meal module creates a complete module based on the techniques described in this chapter, including tests, documents, exceptions, classes, and functions. Note that the test is almost as long as the other code. You will often see this situation later.

After building the module, you can import it into a Python script, for example, the following script calls the classes and functions in the meal module:

This example uses the standard method of importing the module:

Import Meal

When you run this script, you see the following output:

The next script demonstrates another way to import the module:

From meal Import *

All scripts are as follows:

Note that when you use this import form, you can call the Makelunch and Makebreakfast functions without using the module name meal as a prefix.

The output of this script should be similar to the output from the previous script.

To be very careful with the name of the variable, the name of the sample module is meal, which means that the name cannot be used in any other context, for example, as a variable name. If you do that, you cover the definition of meal as a module, and the following example demonstrates the flaw in this approach.

5.6 Installing the Module

The Python interpreter finds the module in the directory listed in the Sys.path variable, and the Sys.path variable includes the current directory, so you can always use the module in the current path.

In most cases, the Python module needs to be placed in the Site-packages directory, which is not part of the Python standard library.

Modules can be installed using three mechanisms:

A You can manually create an installation script or program

b You can create a setup program for your operating system, such as an MSI file on Windows.

c You can use the handy Python distutils package to create a Python-based installation file.

Python creation Module (Chapter Fifth: modules)

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.