Concise python3 tutorial 10. Module

Source: Internet
Author: User

Introduction

Now you know that you can reuse code in your program by defining functions. But what if you want to reuse a large number of functions in other programs you write?

You may have guessed that the method is to use the module.

There are various ways to write modules, but the simplest way is to create a file suffixed with. py and contain the required functions and variables.

Another method is to compile the python interpreter's local language module.

For example, a module written in C language can be compiled and used by Python code running on the standard Python interpreter.

Modules can be imported by other programs to use their functions. This is why we can use the python standard library.

Let's take a look at how to use the standard library module.

Example:

#! /Usr/bin/Python

# Filename: using_sys.py

Import sys

Print ('the command line arguments are :')

For I in SYS. argv:

Print (I)

Print ('/n/nthe pythonpath is', SYS. Path, '/N ')

Output:

$ Python using_sys.py We Are arguments

The command line arguments are:

Using_sys.py

We

Are

Arguments

The pythonpath is ['', 'c: // windows // system32 // python30.zip ',

'C: // python30 // dlls', 'c: // python30 // lib ',

'C: // python30 // lib // Plat-win', 'c: // python30 ',

'C: // python30 // lib // site-packages ']

Workflow:

First, we useImportStatement ImportSysModule. Essentially, this tells Python that we want to use this module.

The SYS module contains functions related to the python interpreter and its working environment (that is, the system.

When python is executedImport sysStatement, it looks for the SYS module. In this example, sys is one of the built-in modules, so Python knows where to find it.

If the import is not a compilation module, that is, a module written in Python, the python interpreter willSYS. PathFind it in the directory listed in.

(Note: if it was not a compiled module I. e. a module written in Python)

If the module is found, the statements in this module will be executed and then you can use it (Note: Only top-level statements will be executed, that is, the statements in the main block ).

Note that a module is initialized only when it is imported for the first time.

In the SYS moduleArgvPoint number reference meansSYS. argv. It clearly states that this name is part of the SYS module.

Another advantage of this syntax is that it will not conflict with the argv variable of the same name in your program.

The variable SYS. argv is a string list (which will be explained in the subsequent chapter ).

Specifically, SYS. argv is a list containing command line parameters, that is, the parameters passed to your program using the command line.

If you are writing a program using IDE, find the method to specify command line parameters for the program in the menu.

Here, when we executePython using_sys.py We Are argumentsWe usePythonCommand runUsing_sys.pyModule. The subsequent content is the parameters passed to the program.

Python saves them to SYS. argv for our use.

Remember, the name of the script to be run is always the first parameter of SYS. argv.

So in this exampleSYS. argv [0]Is'Using _ SYS. py',SYS. argv [1]Is'We',SYS. argv [2]Yes'Are',Argv [3]Yes'Arguments'. Note the python subscript from0Start rather1.

SYS. PathContains a list of directory names indicating where to import the module.

Observe the program output. The first string of SYS. Path is empty-it indicates that the current directory is also part of SYS. path, which correspondsPythonpathThe environment variables are the same.

This means you can directly import the modules in the current directory. Otherwise, you must put your modules in one of the directories listed in SYS. Path.

Note the directory in which the program runs. This directory is the current directory of the program. RunImport OS; print (OS. getcwd ())You can see the current directory of your program.

(Note: In Windows, SYS. path [0] may not be empty, but the current path is explicitly indicated)

 

Byte compilation File. PyC

The import module is a relatively expensive operation, so python uses some tips to accelerate this process.

One way is to create a suffix. PyCTo convert the program to an intermediate format. (Do you still remember the section about how Python works ?)

The next time you import modules from other files, the PyC file will be very useful-it will greatly increase the import speed, because some operations on the import module have been completed in advance.

In addition, this Byte compilation file is still platform-independent.

 

Note:

The. PyC file is generally created in the same directory as its. py file. If Python does not have the write permission for this directory, the. PyC file will not be created.

 

From... Import...Statement

If you wantArgvImport directly to your program (avoid enteringSYS.), You can useFrom sys import argvStatement.

If you want to import all the names in the SYS moduleFrom sys import *Yes. This statement can be used in any module.

You should avoid using this statementImportStatement instead, because the latter can avoid name conflicts and the program is more readable.

 

Module_ Name __Attribute

Each module has a name, and the module name can be obtained through some statements in the module.

It is very convenient to find out whether the module runs independently or is imported.

As mentioned above, when the module is imported for the first time, the code in the module will be executed. We can change the behavior mode when the module is executed independently.

This can be achieved through the module's_ Name __Attribute. (Note: independent running refers to the script file (/Module) that the program starts to run ))

Example:

#! /Usr/bin/Python

# Filename: using_name.py

If _ name _ = '_ main __':

Print ('this program is being run by itself-service ')

Else:

Print ('I am being imported from another module ')

Output:

$ Python using_name.py

This program is being run by itself

$ Python

>>> Import using_name

I am being imported from another module

>>>

Workflow:

Each Python module has its own_ Name __Definition, if it is'_ Main __'The suggestion is that the module runs independently and we can perform some appropriate processing.

 

Create your own modules

Creating your own modules is simple, but you have been doing this all the time! Because every Python script is a module. You just need to make sure it has. PyExtension.

The following example will give you a clear understanding of it:

Example:

#! /Usr/bin/Python

# Filename: mymodule. py

Def sayhi ():

Print ('Hi, this is mymodule speaking .')

_ Version _ = '0. 1'

# End mymodule. py Compilation

The above is a simple module. As you can see, this is nothing special than our usual Python program.

Remember that the module should be placed in the directory where the program to be imported is located, or inSYS. Path.

#! /Usr/bin/Python

# Filename: mymodule_demo.py

Import mymodule

Mymodule. sayhi ()

Print ('version', mymodule. _ version __)

Output:

$ Python mymodule_demo.py

Hi, this is mymodule speaking.

Version 0.1:

How to work:

Note that we also use the node number to access the module members.

Python makes good use of the same symbol to bring a unique 'python' feeling, so that we don't have to learn more about syntax.

Below is a usageFrom... ImportSyntax version:

#! /Usr/bin/Python

# Filename: mymodule_demo2.py

From mymodule import sayhi, _ version __

Sayhi ()

Print ('version', _ version _) Python en: modules 59

Mymodule_demo2.pyAndMymodule_demo.

Note: If you importMymoduleThe same name already exists in the module_ Version __.

In fact, this is likely to happen because every module uses_ Version __Declaring its version is a common practice.

Therefore, we recommend that you give priorityImportStatement, although it may make your program longer.

You can also use:

From mymodule import *

This will import all the public names of the module, suchSayhiBut will not import_ Version __Because it starts with a double underline.

 

PythonZizhen

A guiding principle of python is "clear and better than concealed ".Import thisYou can see the complete content.

The discussion here lists examples of each principle (http://stackoverflow.com/questions/228181/zen-of-python)

 

DirFunction

You can useDirThe function lists all identifiers defined by an object. For example, for a module, identifiers include functions, classes, and variables.

When youDir ()A function provides a module name that returns all the names defined in it.

WhenDir ()If the parameter is null, all names defined in the current module are returned.

Example:

$ Python

>>> Import sys # obtain the attribute list of the SYS module.

>>> Dir (sys)

['_ Displayhook _', '_ Doc _', '_ thook _', '_ name __',

'_ Package _', '_ stderr _', '_ stdin _', '_ stdout _', '_ clear_type_cache ',

'_ Compact_freelists', '_ current_frames', '_ getframe', 'api _ version', 'argv ',

'Builtin _ module_names ', 'byteorder', 'Call _ tracing', 'callstats', 'copyright', 'displayhook ',

'Dlhandle', 'dont _ write_bytecode', 'exc _ info', 'mongothook', 'exec _ prefix', executable ',

'Exit ', 'flags', 'float _ info', 'getcheckinterval', 'getdefaultencoding ', 'getfil

Esystemencoding ', 'getprofile', 'getrecursionlimit ', 'getrefcount', 'getsizeof ',

'Gettrack', 'getwindowsversion', 'hversion', 'intern', 'maxsize', 'maxunicode ',

'Meta _ path', 'modules', 'path', 'path _ hooks', 'path _ importer_cache ', 'platform ',

'Prefix', 'ps1', 'ps2 ', 'setcheckinterval', 'setprofile', 'setrecursionlimit ',

'Settrack', 'stderr', 'stdin ', 'stdout', 'subversion', 'version', 'version _ info', 'waroptions', 'winver']

>>> Dir () # obtain the attribute list of the current module.

['_ Builtins _', '_ Doc _', '_ name _', '_ package _', 'sys ']

>>> A = 5 # create a new variable 'A'

>>> Dir ()

['_ Builtins _', '_ Doc _', '_ name _', '_ package _', 'A ', 'sys ']

>>> Del A # Delete name

>>> Dir ()

['_ Builtins _', '_ Doc _', '_ name _', '_ package _', 'sys ']

Workflow:

First, we use the importedSysModule applicationDirFunction. You can seeSysContains many attributes.

Next, we will not provide parameters for the Dir function. By default, it returns the attribute list of the current module. Note that the imported module list is also part of the current module list.

To observe that dir determines the function, we define a new variable.AAssign a value to it and then test the return value of Dir. We find that the returned list does exist.

With a variableAValue of the same name. When we useDelAfter the statement deletes the variable/attribute of the current module, the change is again reflected in the output of the Dir function.

Del annotation-this statement is used to delete a variable/name. In this example,DelThen you cannot access the variable.A-Like it never exists.

Note:Dir ()Functions can be used for any object. For exampleDir (print)Learn more aboutPrintFunction attribute, orDir (STR)ListStrClass attributes.

 

Package

Now, you must begin to focus on organizing your program layers.

Variables are within the function, while functions and global variables are usually within the module. How to organize modules? This is the turnPackageDebut.

PackageOnly a folder containing modules with a special file_ Init _. pyIt indicates that the python folder is special because it contains the python module.

Let's assume that you need to create'World', Including'Air','Africa'.

The following shows how to organize the folder structure:

-<Some folder present in the SYS. Path>/

-World/

-_ Init _. py

-Asia/

-_ Init _. py

-India/

-_ Init _. py

-Foo. py

-Africa/

-_ Init _. py

-Madagascar/

-_ Init _. py

-Bar. py

 

Packages are only used for hierarchical organizational modules. You will see many of its applications in the standard library.

 

Summary

Just as a function is a reusable part of a program, a module is a reusable program.

Package is used to organize the hierarchy of modules. The standard library that comes with python is an example of a set of packages and modules.

We have seen how to use these modules and how to create your own modules.

Next, we will learn an interesting concept-data structure.

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.