Python programming (5)

zhaozj2021-02-08  206

Chapter 6 module

If you exit the Python interpreter and then enter, the original definition (function, and variable) is lost. So, if you need a program that you need to write a point, it is best to use a text editor to prepare your input, and then run the Python interpretation in the program file as an input, which is called the Preparation Script (Script). When your program grows long, it is best to split it into several documents to facilitate maintenance. You may also want to use a very convenient function in several programs, but do not want to assign a function to assign a function to each program.

In order to support these, Python has a way to place the definition in a file and then call in a script or interactive operation. Such files are called a module; the definition in the module can import other modules or main modules (the main module refers to the variable set that the program is enabled by the script executed by the program or the program executed by the program).

The module is a file containing the Python definition and statement. The file name is composed of the module name plus the suffix ".py". In the module, the name of the module (as a string) can be known by the value of global variable __name__. For example, in the search path of Python, use the text editor you used to use (Python 1.5.2 contains a IDLE integration development environment written with Tkinter, MS Windows has a PythonWIN interface, you can also make Python program editing) Generate a name For "Fibo.py" files, include the following:

# Fibonacci NumBers Module

DEF FIB (N): # outputs a Fibonacci sequence less than n

A, b = 0, 1

While B

Print B,

A, B = B, A B

DEF FIB2 (N): # Returns a Fibonacci sequence less than n

Result = []

A, b = 0, 1

While B

Result.Append (b)

A, B = B, A B

Return RESULT

Then enter the Python interpreter (you can directly enter the interpreter window in iDLE or Pythonwin), and use the following command to import modules:

>>> IMPORT FIBO

This does not introduce the names of the function in the module FIBO into the current symbol table, which is just introduced by the module name FIBO. You can use the module name to access the function:

>>> FIBO.FIB (1000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

>>> FIBO.FIB2 (100)

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

>>> FIBO .__ name__

'Fibo'

If you often use a function, you can give it a partial name:

>>> FIB = FIBO.FIB

>>> FIB (500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

6.1 Further introduction of the module

In addition to the function definition, the module may contain an executable statement. These executable statements are used to initialize the module, which is only performed when the module is first imported.

Each module has its own private symbol table, which is whose global symbol table is for all functions in the module. Therefore, module authors can use global variables in the module without worrying about the global variable conflicts with module users. On the other hand, if you have a grasp, you can use the format of the function in the module, namely the MODNAME.ItemName method to modify the global variables in the module.

Modules can import other modules. We usually place all import statements in the start position of the module (or script), which is not a predetermined requirement. The imported module name is placed in the global symbol table of the module. There is also another usage to import the names in the module into the user's symbol table. E.g:

>>> from FIBO IMPORT FIB, FIB2

>>> FIB (500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not import the module name into the user's symbol table (for example, the FIBO is not defined).

There is also a way to import all the names defined in a module:

>>> from FIBO IMPORT *

>>> FIB (500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

This can import all the names ending in the module.

6.1.1 Module Search Path

When importing a module named spam, the interpreter is first looking for files named "spam.py" in the current directory, then looks for from the list of environment variables PythonPath. PythonPath's usage and executable search path PATH usage is the same, are a list of directory. When PythonPath is not set, or the file is still not found, the search continues to set the default path search set when installed, in UNIX, this is usually ".: / Usr / local / lib / python".

In fact, the module is the path search specified by the variable sys.path, which initializes the directory (or the current path), PythonPath, and installed the default path when the program is initialized. In this way, the user can modify and replace the module search path by modifying sys.path. See the section on the standard module later.

6.1.2 "Compilation" Python File

In order to improve the start time of the small program that calls many standard modules, an important measure is that if there is a file named "spam.pyc" in the directory of "spam.py", this file is considered to contain module spam. A so-called "byte compilation" version. The modification time used to generate "spam.pyc" is recorded in "spam.pyc", ignore the compilation file if the recorded modification time is not consistent with the time of the current file.

It is generally not required to generate a compilation file such as "spam.pyc". Whenever the "spam.py" successfully compiled after the program, try to write the compiling version "spam.pyc". If it is not written, it will not be wrong; if some reason this file is not written, the "spam.pyc" is generated Identify is incomplete and neglected. The format of the compilation file "spam.pyc" is not dependent on the platform, so the machines of different structures can share the Python module directory.

Here is some tips for experts:

If the Python interpreter is started with the -o flag, an optimized compile code is generated, saved in the ".pyo" file. Current optimization is not a lot, now just remove the Assert statement and set_lineno directive. When using the -O flag, all bytecodes are optimized, ". Pyc" file is ignored, ". Py" file is compiled into an optimized bytecode. Optimized code generated by the Python Interpretation of Two Optimization Signs (-oo) sometimes causes the program to run abnormal. Current dual optimization only deletes the __doc__ string from the bytecode, making the ".pyo" file smaller. Some programs may depend on the document string, so this optimization can only be used when aware of awareness does not have problems. Programs read from ".pyc" or ".pyo" cannot be more running faster than from ".py", they just transfer speed faster. If a program is running in the way the script file name is specified in the command line, the script's bytecode will not write ".pyc" or ".pyo" file. So if the main code of the program is moved into a module, only the boot program that imports the module in the script can slightly shorten the startup time of the script. There can be a file called "spam.pyc" (when using the -O flag "spam.pyo") without a corresponding source file "spam.py". This can be used to distribute a Python code base that is more difficult to compile. Module CompileAll can compile all modules in a directory into a ".pyc" file (compiled as ".pyo" file when the -o option is specified). 6.2 Standard Module

Python has a standard module library, which is described in another document "Python Library Reference". Some modules are directly incorporated into the interpreter, which are not the core of the language, in order to run efficiency or to provide an interpretation program in order to provide system underlayer such as system call. Provide those modules are selected at the time of compile, for example, the AMOEBA module can only be available in systems that provide AMOEBA underlying instructions.

There is a module to pay special attention to: SYS module, each Python interpreter is compiled into this module. Variables sys.ps1 and sys.ps2 define initial hints and continuation tips for interactive operation.

>>> IMPORT SYS

>>> SYS.PS1

'>>>'

>>> SYS.PS2

'...'

>>> SYS.PS1 = 'C>'

C> Print 'Yuck!'

Yuck!

C>

These two variables are only defined when interpreting programs run in interactive.

The variable sys.path is a string list, which determines the module search path of the interpreter. It is initialized to the default path specified by environment variable pythonpath, and the environment variable is not defined by the default path to the installation. You can modify this search path with a standard list, for example:

>>> IMPORT SYS

>>> sys.path.append ('/ ufs / guido / lib / python')

6.3 DIR () function

The built-in function DIR () is used to list the names defined by a module, which returns a list of strings:

>>> Import Fibo, SYS

>>> DIR (FIBO)

['__name__', 'Fib', 'FIB2']

>>> DIR (SYS)

['__name__', 'argv', 'Builtin_Module_names', 'Copyright', 'Exit',

'Maxint', 'Modules', 'Path', 'PS1', 'PS2', 'SetProfile', 'Settrace', 'stderr', 'stdin', 'stdout', 'Version']

DIR () lists the names of the current definition when there is no argument.

>>> a = [1, 2, 3, 4, 5]

>>> Import Fibo, SYS

>>> FIB = FIBO.FIB

>>> DIR ()

['__name__', 'A', 'Fib', 'FIBO', 'SYS']

Note DIR () lists all kinds of names: variable name, module name, function name, and so on. DIR () does not list the built-in functions, the name of the variable. To list the built-in name, you need to use the standard module __builtin__:

>>> IMPORT __BUILTIN__

>>> DIR (__ builtin__)

['Accesserror', 'AttributeError', 'Conflicterror', 'EofError', 'Ioerror',

'ImportError', 'IndexError', 'Keyerror', 'KeyboardInterrupt',

'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',

'Syntaxerror', 'systemerror', 'systemexit', 'TypeError', 'ValueError',

'ZerodivisionError', '__name__', 'ABS', 'Apply', 'Chr', 'CMP', 'COERCE',

'Compile', 'Dir', 'Div ModmoD', 'Eval', 'Execfile', 'Filter', 'Float',

'getattr', 'HASATTR', 'HASH', 'HEX', 'Id', 'Input', 'Int', 'LEN', 'LONG',

'Map', 'Max', 'Min', 'Oct', 'Open', 'ORD', 'POW', 'RANGE', 'RAW_INPUT',

'reduction', 'reload', 'repr', 'round', 'setttr', 'str', 'type', 'xrange']

6.4 pack

Python can use the "package" to organize the module name space of Python. You can use the "Band name" when the name is referenced. For example, the module name AB represents a sub-module name "B" name "A". Just as using modules The author of different modules can not be concerned with each other's global variable name conflicts, using a point-to-point module name to make multiple modules such as numpy and PIL don't need to worry about each other's module name conflict. Suppose you have a series of processing sound files And sound data module (called a "package"). There are many different sound file formats (usually using extensions, such as "WAV", "AIFF", ". Au", you may need Making and maintaining a set of increasing modules to handle conversion of different file formats. You may also need to make many different operations on sound data (such as mixing, resonance, balance, generating analog stereo effect), so you need to grow increasing Modules to perform these operations. Take it is the possible structure of your package (represented by a hierarchical file system):

Sound / top package

__init__.py Initialized Sound Pack

Formats / Sub-order package for file format conversion

__init__.py

WAVRead.py

WAVWRITE.PY

AIFFRead.py

AIFFWRITE.PY

Auread.py

Auwrite.py

...

Effects / Sub-process package for sound effects

__init__.py

echo.py

Surround.py

REVERSE.PY

...

Filters / Sub-program for filtering

__init__.py

Equalizer.py

vocoder.py

Karaoke.py

...

The "__init__.py" file in the package directory is required to indicate that Python sees this directory into a package, which prevents the same name, such as "String" subdirectory covering the module definitions that appear behind the search path. In the simplest case, "__ init__.py" can be an empty file, which can also include the code required for the initialization package, and set "__all__" variables, which will be discussed later.

Users can import separate modules from the package, such as:

Import snound.effects.echo

This can import the submodule Sound.effects.echo. To reference it, you must use a full name, for example:

Sound.effects.echo.echofilter (Input, Output, Delay = 0.7, Atten = 4)

Another way to import sub-modules is:

From Sound.effects Import Echo

This also imports the submodule ECHO, but does not need to write a prefix when calling, so you can use:

Echo.ecHofilter (Input, Output, Delay = 0.7, Atten = 4)

Another way of writing is to import the required functions or variables:

From Sound.effects.echo Import Echofilter

This time, the child module echo is also transferred, but its function echofilter can use:

Echofilter (Input, Output, Delay = 0.7, Atten = 4)

Note When using the "FROM package import item", the imported item can be a submodule (or sub-package) of the package, or other names defined within the package such as functions, classes, and variables. The import statement first looks out if the package defines the desired item, if not, it is assumed that it is a module and then transferred. If you can't find it, the result causing importerror. Conversely, when using the format "Import Item.subitem.subsubitem", in addition to the other items should be a package, the last item can be a package or a module, and it is not allowed to be an internal definition. Class, function or variables.

6.4.1 Import from the package *

Now, what happens if the user wrote "from Sound.effects IMPORT *"? Ideally we hope that this should scan the file system to find the submodules in all packs and import them into in. Unfortunately, this operation cannot be accurately implemented on the Mac and Windows platforms, and the two operating systems do not have accurate information on the case of the file name. On these platforms, you don't know that files named "echo.py" will be used as modules Echo, Echo or ECHO is imported. (For example, Windows 95 always writes the first letter in writing when the file name is displayed). DOS 8 3 file name restrictions have caused interesting difficulties to long module names.

The only solution for this problem is the index of the module author explicitly providing the package. The import statement introduced * follows: If the "__init__.py" file of the package defines a list named "__all__", this list is the name table of all modules to import from the package from the package. Therefore, when the new version of the package is released, the author needs to make sure that this list is the latest. This usage can not be supported if the author of the package does not need to be imported. For example, the file SOUNDS / EFFECTS / __ init__.py can contain the following code:

__all__ = ["Echo", "Surround", "Reverse"]

This means that from snound.effects import * will import the specified three subcles from the Sound package.

If you do not define __all__, the from snound.effects import * statement does not import all submodules in the Sound.effects package; this statement can only guarantee Sound.effects imported (may be executing its initialization code "__init_.py") And import the names directly defined in the package. This includes any name and explicitly imported submodule name defined by "__init__.py". This also includes a sub-module that has been explicitly imported in the module, for example:

Import snound.effects.echo

Import snound.effects.surround

From Sound.effects Import *

In this example, the Echo and Surround modules are imported into the current namespace because they have defined when the FROM ... IMPORT statement is executed (in the case of defining __all__, this is also established).

Note that users should try to avoid importing * of * from modules or packages, as this often results in code of readability. Despite this, the number of knockles can be saved with imported * while interacting operation, and some modules take into account this problem when designing, and they only output a certain name. Note that the usage of the FROM package IMPORT-specific submodule is not wrong. In fact, this is still our recommended usage unless the program needs to use the submodule from the same name from other packages.

6.4.2 Internal reference

Submodules often need to reference each other. For example, the module Surround may use the module ECHO. In fact, this is very common, so the import statement first looks for the submodule to be imported from the packet of the submodule to search for the path search. So, the module surround will write as long as IMPORT Echo or from echo import echofilter. If you do not find the module you want to import in the package containing this module, the import statement will look for the top module of the specified name. When the package is organized into a sub-package (such as the Sound Pack in Example), there is no simple approach to reference the submodule in the brothers - the full name of the sub-module must be used. For example, if the module Sound.Filters.vocod is to reference the Echo module in the Sound.effects package, it can use Sound.effects Import Echo.

转载请注明原文地址:https://www.9cbs.com/read-2244.html

New Post(0)