Python Guide (CCAT Translation)

xiaoxiao2021-03-06  43

Foreword

Copyright © 2001, 2002, 2003 Python Software Foundation. All Rights Reserved.

Copyright © 2000 Beopen.com. All Rights Reserved.

Copyright © 1995-2000 Corporation for National Research Initiatives. All Rights Reserved.

Copyright © 1991-1995 Stichting Mathematisch Centrum. All Rights Reserved.

See the end of this document for completion.

summary:

Python is a powerful language that is easy to learn. It includes an efficient advanced data structure that provides a simple but very effective way for object-oriented programming. Python elegant grammar, dynamic data type, and its interpreter make it a scripting language that is applied to various fields and development environments on most platforms.

The source code and compiled version of the Python interpreter and its extended standard library can be available free of charge from Python's Web site http://www.python.org/ and all mirror stations and freely release. Some third-party modules, programs, tools, and additional documents of Python are also available on this site.

Python's interpreter is easy to achieve an extension of functionality and data structures through C or C (or other languages ​​that can be called by c). Because of some Python is also very suitable as an extension language for custom applications.

This manual introduces some basic knowledge and root of Python language and its system. This helps Python has a basic understanding, of course, all examples are included, so this manual is ideal for offline reading.

For a detailed introduction of standard objects and modules, please query the Python library reference manual documentation. The Python Reference Manual provides more formal instructions on language. You need to write C or C extensions, read the extension and integration of the Python interpreter and the Python / C API reference manual. These books covers Python knowledge on each depth.

This manual does not cover all of Python, nor does it explain all related knowledge used. Instead, it introduces many of the most striking functions in Python, which will help the reader's style of this language. After reading it, you should be able to read and write Python modules and programs, follow you can learn from the Python Library Reference Manual to learn the Python complex library and module.

Appetizer

If you have written a large-scale shell script, you should have this experience: you still want to add some other functions, but it is too big, too slow, too complicated; or this function needs to call a system Function, or it is only suitable to call through C ... Usually these problems are not enough to seriously write this shell; probable, this feature requires some similar bell strings or other data that is easy to find in the shell script Type (such as an ordered list of filenames), but they use C to achieve a lot of work, or you are not very familiar with C.

Another case: You may need to use a few C libraries to work, usually the write / compilation / test / compilation cycle is too slow. You need to develop software as soon as possible. Maybe you need to write a program that uses the extension language, but don't want to design a language and write a debugging an interpreter for this, then integrate it into your program.

In the case of the above situation, Python may be the language you are looking for. Python is easy to get started, but it is a real programming language that provides a larger structure than a shell, supports large programs. On the other hand, it provides a more error check than C, and as a high-level language, it has built-in advanced data types, such as variable groups and dictionaries, if implemented by C, these work may make You have a big time for a few days. Because there is more general data types, Python is suitable than awk and even Perl, in other fields, Python is more easier than other languages. Python allows you to divide your program into different modules so that you can reuse in other Python programs. This allows yourself to learn Python program based on a large standard module set or use them as an example. There are some similar file I / O, system calls, sockets, and even user graphics interfaces like TK.

Python is an interpreted language because it does not need to compile and link, it can help you save some development time. The interpreter can be used interactively, which can be very convenient to test the various functions in the language to facilitate writing procedures, or to perform themselves. You can also be a calculator that is useless.

Python can write a very compact and readable program. Programs written with Python are usually much shorter than the same C or C programs, because the following reasons:

The advanced data structure allows you to express a very complex operation in a separate statement; the organization of statements depends on indentation instead of the begin / end block; no variable or parameter declaration.

Python is executable: If you will write a program with a C language, you can easily add new integrated modules and features to the interpreter, or optimize the bottleneck to achieve the maximum speed, or enable Python to be linked to the desired Binary architecture (such as a dedicated business graphics library). When you are really familiar with this, you can integrate Python into the program written by C, put Python as the extension or command line language of this program.

By the way, the name of this language comes from the BBC's "Monty Python's Flying Circus" program, and there is no relationship with ferocious crawler. Quote Monty Python allusions in the document are not only allowed, but also encouraged!

Now you have already understood all exciting things in Python, probably try it carefully. The best way to learn a language is to use it, you will be very happy.

In the next section, we will make very mechanical descriptions of the use of the interpreter. This is not mysterious, but it helps us to practice the example behind it.

This guide other portions describe the various functions of the Python language and the system, starting to be simple expressions, grammar, and data types, followed by functions and modules, and finally advanced content such as exceptions and custom classes.

2. Using the Python Interpreter

2.1 call interpreter

Usually Python's interpreter is installed in the / usr / local / bin / python directory of the target machine; put the / usr / local / bin directory into your UNIX shell's search path, make sure it can be entered

Python

Come start. Because the installation path is optional, it is also possible to install other locations, you can contact users or system administrators installing Python. (For example, / usr / local / python is a very common choice)

Enter a file end value (Unix is ​​Ctrl D, WindWOS is a CTRL Z) interpreter exits 0 value (that is, there is no error, normal exit-translator). If this doesn't work, you can enter the following command to exit: "import sys.exit ()". The line editing function of the interpreter is not very complicated. The interpreter installed on UNIX may have a GNU Readline library support, so you can give additional interactive editing and history. The most convenient way to check the command line editor support is to enter Ctrl P at the primary prompt. If there is a beep (computer speaker), you can use the command line editing function, you can find the shortcut key from Appendix A. If there is no sound, or P is displayed, indicating that the command line editing function is not available, you only use the retractable to delete the input command.

The interpreter operates Some like UNIX Shell: When using a terminal device as a standard input to call it, interpretation and execution commands of the interpreter interactively, when the file name parameter is used as a standard input device, it is interpreted from the file and Execute the script.

The third method of the start interpreter is "Python -c Command [Arg] ...", this method can perform the statement directly in the command line, equivalent to the SHELL-C option. Because the Python statement usually includes special characters such as spaces, it is best to pack the entire statement with double quotes.

Note "Python File" and "Python

When using a script file, you often run the script and then enter your interactive mode. This can also be implemented by adding the -i parameter before the script. (If the script comes from standard input, you can't run this, just like the previous paragraph.)

2.1.1 Parameter Pass

When calling the interpreter, the script name and additional parameters are incorporated into a string list named Sys.Argv. When there is no script and parameters, it also has at least one element: sys.argv [0] is an empty string. When the scripn name is specified as '-' (indicating the standard input), sys.argv [0] is set to '-', when using the -c command, sys.argv [0] is set to '-C'. The parameter after the -c command will be intercepted by the Python interpreter's option processing mechanism, but stay in sys.argv for scripting command operations.

2.1.2 Interactive mode

When you read the command from the TTY, we call the interpreter to operate in interactive mode. In this mode it is executed according to the primary prompt, the main prompt usually identifies three larger than the number (">>"); the continued portion is called the slave prompt, from three points ("... ... "). Before the first line, the interpreter prints welcome information, version number, and authorization tips:

Python

Python 2.3 (# 1, Jul 30 2003, 23:22:59)

[GCC 3.2 20020927 (prenderase)] on cygwin

Type "Help", "Copyright", "Credits" or "license" for more information. >>>

Enter multiplexes When you need a slave prompt, for example, the following IF statement:

>>> THE_WORLD_IS_FLAT = 1

>>> IF the_world_is_flat:

... Print "Be Careful Not to Fall Off!"

...

Be Careful Not to Fall Off!

2.2 Interpreter and its environment

2.2.1 Error handling

When there is an error, the interpreter prints an error message and stack tracking (monitor). . In interactive mode, it returns to the main prompt if it is executed from the file input, which exits in a non-zero state after the print stack tracker. (Exception can be controlled by the Except clause in the TRY statement, so that the error message above will not appear) Some very fatal errors cause to exit in non-zero state, which is usually caused by internal contradictions and memory overflows. All error messages are written to a standard error stream; the ordinary output written in the command is written.

In the primary prompt or an ensemble, enter the intermission (usually Control-C or DEL) will cancel the current input and return to the primary command line. 2.1 Enter a interrupt when performing a command will throw a keyboardInterRupt exception, which can be cut by the TRY sentence.

2.2.2 Executing a Python script

In the BSD system, the Python script can be executed directly like the shell script, as long as you write a line command in the script file, specify file and mode:

#! / usr / bin / env python

(Use the User Path Notification Interpreter) "#!" Must be the first two characters of the file, on some platforms, the first line must end in the Unix style end of the Unix style ("/ n"), cannot use Mac ( "/ R") or end of Windows ("/ r / n"). Note that "#" is the starting fractal of Python is a row comment.

The script can specify execution mode and permissions via the chmod command.

$ chmod x myscript.py

2.2.3 Source Program Coding

Python's source files can be encoded using a character set other than ASCII. The best practice is to define the character set with a special annotation line behind the #!

# - * - CODING: ISO-8859-1 - * -

According to this statement, Python will convert the characters in the file to Unicode, in this case, this character set is ISO-8859-1. In the Python Library Reference Manual, you can find a list of available codes (according to my experiment, Chinese seems to only use CP-936 or UTF-8, not directly support GB, GBK, GB-18030 or ISO-10646 - Translator's Note ).

If your file editor supports the UTF-8 format, you can save the UTF-8 tag (AKA BOM - BYTE ORDER MARK), you can use this instead of the coding declaration (it seems that at least Jext does not support this, and Vim, I haven't found its code to set it, or I am old, and I've specified the encoding of the source code - Translator's Note). IDLE can support it by setting Options / General / Default Source Encoding / UTF-8. It should be noted that the old Python does not support this tag (Python 2.2 or earlier), it also cannot support the operating system to support #! File. Using UTF-8 internal code (whether with markers or coding declarations), we can use most of the world in strings and comments. Non-ASCII character sets cannot be used in the identifier. In order to display all characters correctly, you must save the file as a UTF-8 format in the editor, and use the font of all characters in the file.

2.2.4 Startup file for interactive environment

When using the Python interpreter, we may need to execute some commands at each interpreter. You can include the command you want to perform in a file, set a environment variable named PythonStartup to specify this file. This is similar to the .profile file of UNIX shell.

This file is read-only in the interactive session period. When Python interprets the file from the script or as a terminal as an external command source (although their behavior is very like being in the interactive session period.) Its and interpreters The executed command is in the same namespace, so everything it defines or references can be used in unrestricted uses in the interpreter. You can also change SYS.PS1 and SYS.PS2 instructions in this file.

If you want to perform an additional startup file in the current directory, you can add the following code: "if os.path.isfile ('. Pythonrc.py'): execfile ('. Pythonrc.py '). If you want to use the boot file in a script, you must write such a statement in the script:

IMPORT OS

Filename = os.environ.get ('PythonStartup')

IF filename and os.path.isfile (filename):

EXECFILE (filename)

footnote

... Note:

2.1

An error in the GNU Readline package may result in normally.

Subdirectory

3.1 Preliminary Understanding Python

3.1.1 Value 3.1.2 String 3.1.3 Unicode String 3.1.4 Link Picture 3.2 Start Programming

3. Python's informal introduction

In the following example, the method of distinguishing the input and output is to see if there is a prompt ("> "and" .. "): If you want to repeat these examples, you have to enter all everything after the prompt is displayed. There is no line starting with the prompt, which is the information output by the interpreter. It should be noted that the slave prompt in the example is used for the end of the multi-line command, indicating that you need to enter an empty line.

Many examples in this manual include comments, and even have some folding in the interaction prompt. The comments in Python are started at the end of the current row until the symbol "#". Note You may appear in a row, or you may follow the space or program code, but do not appear in the string, the # number in the string is only the ##.

Example:

# this is the first comment

Spam = 1 # and this is the second comment # ... and now a think!

String = "# this is not a comment."

3.1 Preliminary Understanding Python

Let us test some simple python commands. Start the interpreter then wait for the main prompt ">>>" (this can't be used for too long).

3.1.1 value

The behavior of the interpreter is like a calculator. You can enter it into an expression, it will return the result. The expression of the expression is easy to understand: , *, / and most languages ​​(such as C or PASCAL), parentheses for packets. E.g:

>>> 2 2

4

>>> # this is a comment

... 2 2

4

>>> 2 2 # and a comment on the Same Line as cot

4

>>> (50-5 * 6) / 4

5

>>> # Integer Division Returns The Floor:

... 7/3

2

>>> 7 / -3

-3

Like C, the equal sign ("=") is used to assign a variable. The assigned value is read-only.

>>> width = 20

>>> HEIGHT = 5 * 9

>>> Width * Height

900

The same value can be assigned to several variables at the same time:

>>> x = y = z = 0 # zero x, y and z

>>> X

0

>>> Y

0

>>> Z

0

Python fully supports floating point numbers. When different types of operands are mixed together, the operator converts integers into floating point numbers.

>>> 3 * 3.75 / 1.5

7.5

>>> 7.0 / 2

3.5

The complex is also supported, and the imaginary part is represented by a suffix "j" or "j". The complex number of non-zone is "(Real Imagj)", or can be created via the "Complex (Real, IMAG)" function.

>>> 1J * 1J

(-1 0J)

>>> 1J * Complex (0, 1)

(-1 0J)

>>> 3 1J * 3

(3 3J)

>>> (3 1J) * 3

(9 3J)

>>> (1 2J) / (1 1J)

(1.5 0.5J)

The complex is always represented by the number of floating point numbers and the virtual portion. The real and imaginary part of the plural z is possible from Z.Real and Z.ImAg.

>>> a = 1.5 0.5J

>>> A.Real

1.5

>>> a.imag

0.5

Functions used to floating point numbers and integer (FLOAT (), int () and long ()) cannot work to multiplexes - there is no way to convert the complex into real numbers. It can be used to obtain its model using ABS (z), or you can get its real part through Z.Real.

>>> a = 3.0 4.0J

>>> Float (a)

TRACEBACK (MOST RECENT CALL LAST):

FILE "", line 1, in? Typeerror: can't convert complex to float; use e.g. ABS (z)

>>> A.Real

3.0

>>> a.imag

4.0

>>> ABS (a) # SQRT (A.Real ** 2 a.imag ** 2)

5.0

>>>

In interactive mode, the last expression output is saved in the _ variable. This means that when you use the desktop calculator, it can make continuous calculations, for example:

>>> TAX = 12.5 / 100

>>> price = 100.50

>>> Price * TAX

12.5625

>>> price _ _ _ _

113.0625

>>> Round (_, 2)

113.06

>>>

This variable is read only for users. Don't try to give it a value - Due to Python's grammatical effect, you will only create a partial variable of the same name overwritten it.

3.1.2 String

In addition to values, Python can also operate strings through several different ways. String use single quotes or double quotes:

>>> 'Spam Eggs'

'spam eggs'

>>> 'DOESN /' T '

"doesn't"

>>> "doesn't"

"doesn't"

>>> '"YES," He SAID.'

'"Yes," He Said.'

>>> "/" yes, / "he said."

'"Yes," He Said.'

>>> '"ISN /' T," SHE SAID. '

'"ISN /' T," SHE SAID. '

Strings can be branched in several ways. It can be used as a continuation in the playback backslash, indicating that the next line is the logic of the current line.

Hello = "this is a rather long string containing / n /

Several Lines of Text Just As You Would Do IN C./N/

Note That Whitespace At the beginning of the line is /

Significant. "

Print Hello

Note that the wrap / n is represented; the new row mark behind the backslash (NEWLINE, abbreviation "N") will convert to a newline, and the example is printed as follows:

This is a rather long string containing

Several Lines of Text Just As You Would Do IN C.

Note this whitespace at the beginning of the line is significant.

However, if we create a "RAW" line, the / n sequence does not turn into a wrap, the final backslash and the newline n are data processing in the string. As follows:

Hello = R "this is a rather long string containing / n / several lines of text Much as you would do in c."

Print Hello

Will print:

This is a rather long string containing / n /

Several Lines of Text Much as you would do in C.

Alternatively, the string can be identified with a pair of triple quotation marks "" "or '' '. The string in the triple quotation marks do not need a wrap tag at the end, and all formats are included in the string.

Print "" "

USAGE: Thingy [Options]

-h Display this usage message

-H hostname hostname to connect

"" "

Products The Following Output:

USAGE: Thingy [Options]

-h Display this usage message

-H hostname hostname to connect

The string printing from the interpreter is identical to the form of them: the internal quotation marks, the quotation marks of the backslash and various strange characters, are precisely displayed. If the string contains single quotes, it does not contain dual quotes, you can use double quotes to reference it, and it can be used in single quotes. (The print statement described later can be used to write a string without quotation marks and backslash).

Strings can be used with number (or bonded), or you can cycle with *.

>>> Word = 'Help' 'A'

>>> Word

'Helpa'

>>> '<' Word * 5 '>'

''

The connection between the two string values ​​is automatic. The first line of the previous example can be written as "Word = 'Help' 'A'", which is only valid for the string value, and any string expressions do not apply to this. method.

>>> Import String

>>> 'str' 'ing' # <- this is OK

'string'

>>> String.Strip ('str') 'ing' # <- this is OK

'string'

>>> String.Strip ('str') 'ing' # <- this is invalid

FILE "", LINE 1, in?

String.strip ('str') 'ing'

^

SyntaxError: Invalid Syntax

The string can be queried by the subscript (index); just like C, the first character of the string is 0. There is no independent character type here, and characters are only a string of one. As in ICON, the string of the string can be represented by a slice flag: two indexes separated by colon. >>> Word [4]

'A'

>>> Word [0: 2]

'HE'

>>> Word [2: 4]

'lp'

Slice indexing can use default values; omitted the previous index represents 0, omitting the latter index represents the length of the string of the slice.

>>> Word [: 2] # The first two characters

'HE'

>>> Word [2:] # all but the first two characters

'lpa'

Unlike the C string, the Python string cannot be rewritten. Press the string index assignment to generate an error.

>>> Word [0] = 'x'

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

TypeError: Object Doesn't Support Item Assignment

>>> Word [: 1] = 'splat'

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

Typeerror: Object Doesn't Support Slice Assignment

However, a new string can be generated by simple and effective combination:

>>> 'X' Word [1:]

'Xelpa'

>>> 'SPLAT' WORD [4]

'Splata'

Slice operation has a very useful invariance: s [: i] s [i:] is equal to S.

>>> Word [: 2] Word [2:]

'Helpa'

>>> Word [: 3] Word [3:]

'Helpa'

Degraded sliced ​​index is dealt with very beautiful: Excessive index instead of string size, downlink to an empty string than the upper world.

>>> Word [1: 100]

'ELPA'

>>> Word [10:]

'' '

>>> Word [2: 1]

'' '

The index can be a negative number, the count starts from the right, for example:

>>> Word [-1] # The last character

'A'

>>> Word [-2] # the last-but-one character

'P'

>>> Word [-2:] # The last two characters

'PA'

>>> Word [: - 2] # all but the last two characters

'HEL'

But -0 is still 0, so it is not counting from the right!

>>> Word [-0] # (Since -0 Equals 0) 'h'

The negative slice index of the cross-border is truncated, but don't try to do this in the front element index (non-slice):

>>> Word [-100:]

'Helpa'

>>> Word [-10] # Error

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

IndexError: String Index Out of Range

The best way to understand the slices is the point between the indexes between the two characters. The left side of the first character is 0, and the right side of the nth character in the string is index N, for example:

- - - - -

| H | E | L | P | a |

- - - - -

0 1 2 3 4 5

-5 -4 -3 -2 -1

The first line is the location of the 0 to 5 index given in the string, and the second line is the corresponding negative index. The slice from I to J consists of characters between the two signs.

For non-negative indexes, the length of the slice is the difference in two indexes. For example, the length of WORD [1: 3] is 2.

Built-in function LEN () Returns the length of the string:

>>> s = 'supercalifragilisticexpialidocious'

>>> LEN (S)

34

3.1.3 Unicode string

Starting with Python 2.0, programmers can use a new data type to store text data: Unicode objects. It can be used to store a variety of Unicode data (see http://www.unicode.org/), and, it can be combined with existing string objects by automatic conversion if necessary.

Unicode provides a sequence for all characters in modern and old text. Previously, characters can only use 256 serial numbers, and text usually maps with character mappings by binding code. This is easy to lead to confusion, especially the internationalization of software (INTERNATIONALIZATION - usually writes "I18N" - "I" 18 Characters "N"). Unicode solves this problem by defining a unified code page for all characters.

A Unicode string is defined in Python and define a normal string simple:

>>> U'Hello World! '

U'Hello World! '

The "U" of the quotation marks indicates that the created a Unicode string is created. If you want to join a special character, you can use Python's Unicode-Escape encoding. As shown in the following example:

>>> U'Hello / U0020World! '

U'Hello World! '

The replaced / u0020 identifier indicates a Unicode character (spacer) that is inserted into the encoded value of 0x0020 at a given location.

Other characters will also be interpreted directly into a corresponding Unicode code. If you have a Latin-1 encoded string that is commonly used in Western countries, you can find that the first 256 characters of the Unicode character set are exactly the same as the corresponding character coding of the LATION-1.

In addition, there is a row pattern as a normal string. If you want to use Python's Raw-Unicode-Escape encoding, you need to add a UR prefix before quotes of the string. If there may be more than one backslash before lowering "u", it will only convert those separate / uxxx to Unicode characters. >>> UR'Hello / U0020World! '

U'Hello World! '

>>> UR'Hello // U0020World! '

U'Hellou0020World! '

Row mode is useful when you need to enter a lot of backslashes, which may be used for regular expressions.

As part of these coding criteria, Python provides a complete way to create a Unicode string from known codes.

The built-in function Unicode () provides a method of accessing (encoding and decoding) all registered Unicode encodings. It converts well-known Latin-1, ASCII, UTF-8, and UTF-16. The two variable length coding characters of the later are set with one or more Byte storage Unicode characters. The default character set is ASCII, which only processes the encoding of 0 to 127, rejects other characters and returns an error. When a Unicode string is printed, it is written or converted by STR (), they are replaced by default encoding.

>>> U "ABC"

U'Abc '

>>> STR (U "ABC")

'ABC'

>>> U "ÄÜ"

u '/ xe4 / xf6 / xfc'

>>> STR (u "Äöü")

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

UnicodeEncodeerror: 'Ascii' Codec Can't Encode Characters in Position 0-2: Ordinal Not in Range (128)

To convert a Unicode character to an 8-bit string with the specified character set, you can use the Encode () method provided by the Unicode object, which has a parameter to specify the encoded name. Code name lowercase.

>>> U "ÄÜ" .Encode ('UTF-8')

'/ xc3 / xa4 / xc3 / xb6 / xc3 / xbc'

If you have a specific encoded string, you want to turn it into a Unicode character set, you can use the UNCODE () function, which is the second parameter as a coded name.

>>> Unicode ('/ XC3 / XA4 / XC3 / XB6 / XC3 / XBC', 'UTF-8')

u '/ xe4 / xf6 / xfc'

3.1.4 Link Picture

Python has several composite data types for organizing other values. The most common is the linked list, which is written to a comma-separated one column (child), and the child of the linked list is not necessarily the value of the same type.

>>> a = ['spam', 'Eggs', 100, 1234]

>>> a

['spam', 'Eggs', 100, 1234]

Like a string, the linked list also begins with zero, can be sliced, coupled, and so on:

>>> a [0]

'spam'

>>> a [3] 1234

>>> a [-2]

100

>>> a [1: -1]

['Eggs', 100]

>>> a [: 2] ['Bacon', 2 * 2]

['spam', 'Eggs', 'Bacon', 4]

>>> 3 * a [: 3] ['Boe!']

['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'boe!']

Unlike the constant string, the linked list can change the value of each independent element:

>>> a

['spam', 'Eggs', 100, 1234]

>>> A [2] = a [2] 23

>>> a

['spam', 'Eggs', 123, 1234]

Slice operations can be made, and even change the size of the linked list:

>>> # Replace Some Items:

... a [0: 2] = [1, 12]

>>> a

[1, 12, 123, 1234]

>>> # REMOVE SOME:

... a [0: 2] = []

>>> a

[123, 1234]

>>> # Insert Some:

... a [1: 1] = ['Bletch', 'XYZZY']

>>> a

[123, 'Bletch', 'xyzzy', 1234]

>>> a [: 0] = a # INSERT (a copy of) itself at the beginning

>>> a

[123, 'Bletch', 'XYZZY', 1234, 123, 'Bletch', 'XYZZY', 1234]

The built-in function len () can also be used for linked lists:

>>> LEN (a)

8

It can also nested a list (create another linked list in the linked list), for example:

>>> q = [2, 3]

>>> P = [1, Q, 4]

>>> LEN (P)

3

>>> p [1]

[twenty three]

>>> p [1] [0]

2

>>> P [1] .append ('XTRA') # See section 5.1

>>> P

[1, [2, 3, 'XTRA'], 4]

>>> Q

[2, 3, 'XTRA']

Note that the last example, P [1] and Q actually point the same object! We will tell the object syntax later.

3.2 Start programming

Of course, we can use Python to add 2 more complex things than 2 plus 2. For example, we can output subsequences of the Fibonacci sequence with the following methods:

>>> # Fibonacci Series:

... # the sum of two elements defines the next ... a, b = 0, 1

>>> While B <10:

... Print B

... a, b = b, A B

...

1

1

2

3

5

8

Some new features are introduced in the example:

The first line includes composite parameters: variables A and B are also assigned 0 and 1. In the last line, this technology has proved to make an operation before the expression before the assignment. The expression on the right is calculated from left to right. The While loop runs in the condition for true time. In Python, it is true, zero is fake similar to any non-zero value. This condition can also be used in strings or linked lists, and the truth is true for any sequence type, the length is not zero, and the null sequence is false. The examples used are a simple comparison. The standard comparison operator is written and C. <(less),> (greater than), == (equal to), <= (less than or equal),> = (greater than or equal) and! = (Not equal). The cyclic body is indent: indentation is a method of python's statement packet. Python still does not provide a smart editing feature so you want to enter a Tab or (one or more) spaces at each shrinkage. In fact, you may prepare a more complex text editor to write your Python program, and most text editors provide automatic indentation. When an interactive input is a complex statement, you need to complete it with a blank line (because the interpreter can't guess when you enter the last line). It should be noted that every line must have the same empty character to identify this is the same statement. The PRINT statement prints the value of a given expression. It is different from you to enter the expression you need (just like the previous calculator example), which can output multiple expressions simultaneously. There is no quotation when the string is output, and the items are separated from one space, you can easily distinguish them, as shown below: >>> i = 256 * 256

>>> Print 'The Value of i is', i

The value of i is 65536 The comma at the end of the Print statement avoids the wrap in the output: >>> a, b = 0, 1

>>> While B <1000:

... Print B,

... a, b = b, A B

...

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 What should be noted that if the last line is still not written, the interpreter will insert a new line when it prints the next command.

This section

4.1 IF statement 4.2 for statement 4.3 Range () Function 4.4 Break and Continue statement, and ELSE clause 4.5 PASS statement in loops 4.6 Definition function 4.7 In-depth function definition

4.7.1 Parameter defaults 4.7.2 Parameter Keyword 4.7.3 Variable Parameter Table 4.7.4 Lambda Form 4.7.5 Document String

4. Other process control tools

In addition to the While statement described earlier, Python also borrowed some process control functions from other languages ​​and changed.

4.1 IF statement

Perhaps the statement type of the most sentence is an IF statement. E.g:

>>> x = int (Raw_INPUT ("please enter an integer:") >>> IF x <0:

... x = 0

... Print 'Negative Changed to Zero'

... ELIF X == 0:

... Print 'Zero'

... ELIF X == 1:

... Print 'Single'

... Else:

... Print 'more'

...

There may be 0 or many ELIF portions, and ELSE is optional. Keyword "Elif" is an abbreviation for "else if", which can effectively avoid excessive indentation. If ... ELIF ... Elif ... Sequence is used to replace Switch or CASE statements in other languages.

4.2 for statement

The for statement in Python is slightly different from you in C or PASCAL. The usual loop may define an equivalence step process (such as PASCAL) or by the user to define iterative steps and abort conditions (such as C), Python's For statement in accordance with the child in any sequence (linked list or string), Iterations are performed in the order in the sequence. For example (no fencing):

>>> # Measure Some Strings:

... a = ['Cat', 'Window', 'DefenestRate']

>>> for x in A:

... Print X, Len (X)

...

Cat 3

WINDOW 6

Defenestrate 12

Modify the iterative sequence insecure during iteration (such a case only when using a variable sequence such as a linked list). If you want to modify the sequence of your iteration (for example, copy the selection), you can iterate its replica. This usually uses a slice identification to make this:

>>> for x in a [: # Make a SLICE COPY OF THE ENTIRE LIST

... if len (x)> 6: a.insert (0, x)

...

>>> a

['Defenestrate', 'Cat', 'Window', 'DefenestRate']

4.3 Range () function

If you need a numeric sequence, the built-in function range () may be useful, it generates an equal line-of-one linked list.

>>> RANGE (10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Range (10) Generates a linked list containing 10 values. Its accurate use of the index value of the list filled this length of 10, which does not include end values ​​in the range in the generated linked list. Also allow the RANGE operation to start from another value, or you can specify a different step value (even negative, sometimes it is also called "step size"):

>>> RANGE (5, 10)

[5, 6, 7, 8, 9]

>>> RANGE (0, 10, 3)

[0, 3, 6, 9]

>>> RANGE (-10, -100, -30)

[-10, -40, -70]

If you need iteratory table index, use RANGE () and Len (): >>> as shown below () and LEN (): >>> A = ['Mary', 'Had', 'A', 'Little', 'Lamb']

>>> for i in range (len (a)):

... Print I, A [I]

...

0mary

1 had

2 a

3 Little

4 lamb

4.4 BREAK and Continue statements, and ELSE clauses in the loop

A similar to C is used to jump out of the nearest level for or while loop.

The Continue statement is known from C, which means that the loop continues to perform the next iteration.

The loop can have an ELSE clause; it is executed when a full list (for for for for) or performing the condition is false (for while), but is not performed in the case where the loop is aborted by BREAK. The sample program of the following search prime number demonstrates this clause:

>>> for N in Range (2, 10):

... for x in Range (2, n):

... if n% x == 0:

... Print N, 'Equals', X, '*', N / X

... BREAK

... Else:

... # loop fell through without finding a factory

... Print N, 'Is a Prime Number'

...

2 is a principle Number

3 is a principle Number

4 Equals 2 * 2

5 is a principle Number

6 Equals 2 * 3

7 is a principle Number

8 Equals 2 * 4

9 Equals 3 * 3

4.5 PASS statement

The PASS statement does nothing. It is used in those statements that must have, but don't do anything on the program, for example:

>>> While True:

... Pass # busy-wait for keyboard interrupt

...

4.6 Defining functions

We can write a function to generate a Mippi-Cilia with a given upper industry:

>>> DEF FIB (N): # Write Fibonacci Series Up to N

... "" "" PRINT A FIBONACCI Series Up to n. "" ""

... a, b = 0, 1

... while b

... Print B,

... a, b = b, A B

...

>>> # Now call the function we need jud defined:

... FIB (2000)

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

Keyword DEF introduces a function definition. In response, there must be a function name and a parentheses including the formal parameters. The function state statement begins with the next line, it must be indent. The first line of the function body can be a string value, which is the document string of the function, or can be called DOCSTRING.

Some document string tools can process or print documents online, or browse the code to the user interact; adding a document string in your code, it is a good practice. When the function is called, a new symbol table is introduced for a local variable. All local variables are stored in this partial symbol table. When references parameters, you will look up from the local symbol table, then the global symbol table, then the built-in naming table. Therefore, although global parameters can be referenced, they cannot directly assign (unless they are named using Global statements).

The actual parameter of the function reference is introduced into the local symbol table when the function call is called. Therefore, the actual parameter is always transmitted (the value here is always a object reference, not the value of the object). 4.1 When a function is called by another function, a new local symbol table is created during the calling process.

The function is defined in the current symbol table to introduce a function name. As a user-defined function, the function name has a type value approved by the interpreter. This value can assign other named so that it is used as a function. This is like a rename mechanism:

>>> FIB

>>> f = FIB

>>> f (100)

1 1 2 3 5 8 13 21 34 55 89

You may think FIB is not a function, but a process (Procedure). Python and C are just a function that does not have a return value. In fact, from the technical process, there is also a return value, although it is not a discussion. This value is called None (this is a built-in naming). If a value is just none, the usual interpreter will not write a none, if you really want to see it, you can do this:

>>> Print FIB (0)

None

The following is demonstrated how to return a value of the Numerical chain containing the Philippine desence in the function instead of printing it:

>>> DEF FIB2 (N): # Return Fibonacci Series Up to N

... "" "" Return a List Containing The Fibonacci Series Up to n. "" "

... result = []

... a, b = 0, 1

... while b

... Result.Append (b) # See Below

... a, b = b, A B

... Return RESULT

...

>>> F100 = FIB2 (100) # Call IT

>>> F100 # Write the result

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

As before, this example demonstrates some new Python features:

The RETURN statement returns a value from the function and returns NONE without an expression. The process will return none after the end. Statement Result.Append (b) is a method for the Lin table object Result (Method). The method is a "function of" a "one object, which is named obj.methodename, where the OBJ is an object (may be an expression), MethodeName is a naming of a method in the object type definition. Different types of methods define different methods. Different types may have the same name, but will not be confused. (This may happen when you define your object types and methods, this guide will introduce how to use classes). The Append () method shown in the example is defined by a linked list object, which adds a new element to the linked list. In the example, it is equivalent to "Result = Result [B]", but it is more efficient. 4.7 In-depth function definition

Sometimes you need to define a variable number of parameters. There are three ways to do, and we can use them in combination.

4.7.1 Parameter default value

The most useful form is to specify the default value for one or more parameters. This created function can use fewer parameters when calling.

Def ask_ok (prompt, retries = 4, complaint = 'yes or no, please!'):

While True:

OK = Raw_INPUT (Prompt)

IF OK IN ('Y', 'Ye', 'Yes'): Return 1

IF OK in ('N', 'NO', 'NOP', 'NOPE'): Return 0

RETRIES = Retries - 1

If Retries <0: Raise IoError, 'Refusenik User'

Print Complaint

This function can also be called in the following ways: Ask_ok ('Do You Really Want To Quit?'), Or like this: Ask_ok ('Ok To Overwrite THE?', 2).

The default value is parsed in the function definition segment, as shown below:

i = 5

DEF F (arg = i):

Print Arg

i = 6

f ()

Will Print 5.

Important warning: The default value will only be parsed once. Some differences are generated when the default is a variable object, such as a chain table, a dictionary or most class instance. For example, the following function accumulates its parameter value in successive calls:

DEF F (A, L = []):

L.Append (a)

Return L

Print f (1)

Print f (2)

Print f (3)

This will be printed:

[1]

[1, 2]

[1, 2, 3]

If you don't want to share parameter default values ​​between different function calls, you can write functions as the following instance:

DEF F (a, l = none):

IF l is none:

L = []

L.Append (a)

Return L

4.7.2 Parameter keyword

The function can be called by the form of the parameter keyword, such as "Keyword = Value". For example, the following functions:

DEF PARROT (Voltage, State = 'a stiff', action = 'voom', type = 'Norwegian Blue'):

Print "- this Parrot Wouldn't", Action, Print "If You Put", Voltage, "Volts Through it."

Print "- Lovely Plumage, THE", TYPE

Print "- it's", state, "!"

You can call any of the following methods:

Parrot (1000)

Parrot (action = 'voooom', Voltage = 1000000)

PARROT ('a thousand', state = 'pushing up the daisies')

Parrot ('a million', 'bereft of life', 'jump')

However, the following calls are invalid:

Parrot () # Required Argument Missing (missing required parameters)

Parrot (Voltage = 5.0, 'DEAD') # Non-Keyword Argument Following Keyword (Non-keyword parameters behind the keyword)

Parrot (110, Voltage = 220) # duplicate value for argument (repeated assignment to parameters)

Parrot (actor = 'john cleese') # unknown keyword (unknown keyword)

Typically, each keyword in the parameter list must come from a form parameter, and each parameter has a corresponding keyword. The default value is not important if the form parameter is not important. Actual parameters cannot assign multiple values ​​at a time - form parameters cannot be used in the same call simultaneously using location and keyword binding values. Here is an example to demonstrate the failure of this constraint:

>>> DEF FUNCTION (A):

... Pass

...

>>> Function (0, a = 0)

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

TypeError: function () got multiple value for keyword argument 'a'

When a form of parameters such as ** Name, it receives a dictionary that contains all keyword parameters that have not appeared in the form parameter list. A form of form parameters such as * name may also be used here, which receives a topology (described in detail in the next section), containing all parameter values ​​that do not appear in the form parameter list. (* Name must appear before ** Name), for example, we define a function:

DEF Chezeeshop (Kind, * Arguments, ** keywords):

Print "- do you have any", kind, '?'

Print "- I'm Sorry, We're All Out of", Kind

For arg in arguments: Print Arg

PRINT '-' * 40

Keys = keywords.keys ()

Keys.sort ()

For KW in Keys: Print KW, ':', Keywords [kW] it can call like this:

Chezeeshop ('Limburger', "IT's Very Runny, Sir.",

"It's really, very rueny, sir.",

Client = 'John Cleese',

Shopkeeper = 'Michael Palin',

Sketch = 'Cheese Shop Sketch')

Of course, it will print as follows:

Do you have any limited?

- I'm Sorry, We're All Out of Limburger

IT's Very Runny, SIR.

IT's really, Very Runny, SIR.

----------------------------------------

Client: John Cleese

SHOPKEEPER: Michael Palin

Sketch: Cheese Shop Sketch

Note that the sort () method is called before the keyword dictionary content printing, otherwise, the order of printing parameters is undefined.

4.7.3 Variable parameter table

Finally, a least commonly used option is to allow function to call a variable number of parameters. These parameters are packaged into a topology. Before these variable number of parameters, there can be zero to multiple ordinary parameters:

DEF FPRINTF (File, Format, * Args):

File.write (Format% Args)

4.7.4 Lambda form

For appropriate needs, there are several functions that are usually in functional language and LISP to Python. Through the lambda keyword, you can create a small implicit function (who can tell me, how can this anonymous function? - Translator) Here is a function returned to its two parameters: "Lambda A, B : a b. Lambda forms can be used for any function objects required. For grammar restrictions, they can only have a separate expression. Semantics, they are just a syntax skill in the normal function definition. Similar to the nested function definition, the lambda form can reference variables from the included range:

>>> DEF MAKE_INCREMENTOR (N):

... RETURN LAMBDA X: X N

...

>>> f = Make_incrementor (42)

>>> f (0)

42

>>> f (1)

43

4.7.5 Document String

Here you introduce the concepts and formats of the document string.

The first line should be an introduction to the use of an object. Short start, do not have to clearly state the object name or type because they can be learned from other ways (unless this name is happening to describe the verb described). This line should start with a capital letter and end with the end.

If the document string has multiple lines, the second line should be empty, which is clearly separated from the next detailed description. The next document should have one or more paragraphs describing the call agreement, boundary effect, etc.

Python's interpreter does not remove indentation from a multi-line document string, so it should be cleared by it if necessary. This is in line with the usual habits. The first non-empty line after the first line determines the indentation format of the entire document. (We don't have to use the first line because it is usually tightly relying on the starting quotation marks, the indentation format is unclear.) Dosing white "equivalent" is the start of the string. Each line should not have indentation. If there is indent, all whites should be cleared. It is equivalent to the blank is the test after verification (usually 8 spaces). (This paragraph is translated, there is a question of readers, please refer to the original - translator) The following is an example of multi-line document string:

>>> DEF my_function ():

... "" "" "Do Nothing, But Document IT.

...

... no, real, it doesn't do anything.

... "" ""

... Pass

...

>>> print my_function .__ doc__

Do Nothing, but document it.

NO, Really, It Doesn't do anything.

footnote

... object).

4.1

In fact, it is said

Call object references are more appropriate because if you are incorporated into a variable object, the caller can get any changes generated by the caller (inserted into the subkey).

Subdirectory

5.1 In-depth linked list

5.1.1 Connecting the Links as a Stack Using 5.1.2 Linches as a queue Use 5.1.3 Functional Programming Tools 5.1.4 Link Pictures 5.2 Del Statement 5.3 Topology (SEQUENCES) 5.4 Dictionary (Dictionaries) 5.5 Circular Skills 5.6 In-depth Condition Control 5.7 Compare Sequences (SEQUENCES) and other types

5. Data structure

This chapter explains some things you have learned and have added new content.

5.1 In-depth linked list

There are many ways to list the table, here is all methods of the chain table:

Append (x)

Add an element to the end of the linked list, which is equivalent to

a [len (a):] = [x]

.

Extend (L)

Expand the chain list by adding all the elements of the specified list, it is equivalent to

a [len (a):] = L

.

INSERT (i, x)

Insert an element in the specified location. The first parameter is the index of the element inserted in front of it, for example

A. INSERT (0, x) before being inserted into the entire linked list, and

A.Nsert (Len (a), x) is equivalent to

a.append (x)

.

Remove (x)

Delete the value of the list

The first element of x. If there is no such element, it will return an error.

POP ([i])

Delete the element from the specified location of the linked list and returns it. If no index is specified,

A.POP () Returns the last element. The element is then deleted from the list. (In the method

The square brackets on both sides indicate that this parameter is optional, not asking you to enter a pair of brackets, you will often

Such markers are encountered in the Python Library Reference Manual. )

Index (X)

The first value in the return list is

The index of the elements of x. If there is no matching element, an error will be returned.

Count (x)

return

X The number of times that appears in the linked list.

sort ()

The elements in the linked list are properly sorted.

Reverse ()

Elements in the chain table.

Below this example demonstrates most of the methods of the list: >>> a = [66.6, 333, 333, 1, 1234.5]

>>> Print A.count (333), A.count (66.6), A.Count ('x')

2 1 0

>>> a.insert (2, -1)

>>> A.Append (333)

>>> a

[66.6, 333, -1, 333, 1, 1234.5, 333]

>>> a.index (333)

1

>>> a.Remove (333)

>>> a

[66.6, -1, 333, 1, 1234.5, 333]

>>> a.Reverse ()

>>> a

[333, 1234.5, 1, 333, -1, 66.6]

>>> A.SORT ()

>>> a

[-1, 1, 66.6, 333, 333, 1234.5]

5.1.1 Take the Link Watch as a Stack Used

The chain method allows the linked list to be used as a stack, the stack is such a data structure, the most entered element is released (the next first out). Use the append () method to add an element to the top of the stack. The POP () method that does not specify an index can release an element from the stack top. E.g:

>>> stack = [3, 4, 5]

>>> stack.Append (6)

>>> stack.Append (7)

>>> Stack

[3, 4, 5, 6, 7]

>>> stack.pop ()

Seduce

>>> Stack

[3, 4, 5, 6]

>>> stack.pop ()

6

>>> stack.pop ()

5

>>> Stack

[3, 4]

5.1.2 Take the list as a queue

You can also use the list as a queue, the queue is such a data structure, the first entry element is first released (advanced first out). Using the append () method can add the element to the queue finally, call the POP () method for the parameter to release the first entry element. E.g:

>>> queue = ["Eric", "John", "Michael"]

>>> Queue.Append ("Terry") #TERRY ARRIVES

>>> Queue.Append ("graham") # graham arrives

>>> queue.pop (0)

'ERIC'

>>> queue.pop (0)

'John'

>>> queue

['Michael', 'Terry', 'Graham']

5.1.3 Function Programming Tools

For linked lists, there are three built-in functions: filter (), map (), and reduuce ().

"FILTER (FUNCTION, SEQUENCE" returns a sequence, including an element that returns a value true after all call function (items) in a given sequence. (If possible, the same type will be returned). For example, the following program can calculate the number of partial prime numbers: >>> DEF F (x): return x% 2! = 0 and x% 3! = 0

...

>>> Filter (f, Range (2, 25))

[5, 7, 11, 13, 17, 19, 23]

"MAP (Function, Sequence" is called for each element and returns the return value into a linked list for each element. For example, the following program calculates the cube:

>>> DEF CUBE (X): Return X * x * x

...

>>> Map (Cube, Range (1, 11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

You can pass multiple sequences, and the function must have a corresponding number of parameters. When executed, use the elements corresponding to each sequence to call the function (if some sequences are shorter than other short, use none instead). If None is incorporated into a function, the direct return parameters are replaced.

These two situations we will find "MAP (None, List1, List2) is a convenient way to turn a pair of sequences into elements. E.g:

>>> SEQ = RANGE (8)

>>> Def Square (x): return x * x

...

>>> Map (None, SEQ, MAP (Square, SEQ))

[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]

"Reduce (FUNC, SEQUENCE" returns a single value, which is constructed: first call the function in the first two elements of the sequence, then call the return value and the third parameter, and execute it. For example, the following programs calculate the sum of 1 to 10:

>>> DEF ADD (X, Y): Return X Y

...

>>> Reduce (Add, Range (1, 11))

55

If there is only one element in the sequence, it returns it, and if the sequence is empty, you will throw an exception.

You can pass the third parameter as the initial value. If the sequence is empty, return to the initial value, otherwise the function will first receive the first element of the initial value and the sequence, and then the return value and the next element, so on. E.g:

>>> DEF SUM (SEQ):

... DEF Add (x, y): Return X Y

... Return Reduce (Add, SEQ, 0)

...

>>> SUM (Range (1, 11))

55

>>> SUM ([])

0

Do not define so as examples in the example: Because the total value is a universal demand, the built-in SUM (Sequence) function is provided in the new version 2.3.

5.1.4 Link Picture Detection

Link list provides a simple way to create a list without using MAP (), Filter (), and lambda. The definition of the returned linked list is usually clearer than the created list. Each chain list includes an expression, zero or more for or if statements after a For statement. The return value is a linked list that consists of an element obtained by the expression after the FOR or IF clause. If you want to get a topology, you must add parentheses. >>> Freshfruit = ['Banana', 'loganberry', 'passes fuit']

>>> [weapon.strip () for weapon in freshfruit]

['Banana', 'loganberry', 'passion struit']

>>> VEC = [2, 4, 6]

>>> [3 * x for x in vec]

[6, 12, 18]

>>> [3 * x for x in Vec IF X> 3]

[12, 18]

>>> [3 * x for x in Vec IF x <2]

[]

>>> [[xi x ** 2] for x in vec]

[[2, 4], [4, 16], [6, 36]]

>>> [x, x ** 2 for x in vec] # Error - Parens Required for tuples

FILE "", LINE 1, in?

[x, x ** 2 for x in vec]

^

SyntaxError: Invalid Syntax

>>> [(x, x ** 2) for x in vec]

[(2, 4), (4, 16), (6, 36)]

>>> VEC1 = [2, 4, 6]

>>> VEC2 = [4, 3, -9]

>>> [x * y for x in vec1 for y in vec2]

[8, 6, -18, 16, 12, -36, 24, 18, -54]

>>> [x y for x in vec1 for y in vec2]

[6, 5, -7, 8, 7, -5, 10, 9, -3]

>>> [VEC1 [I] * VEC2 [I] for i in inheng (len (vec1))]

[8, 12, -54]

To make the chain pilot matching the behavior of the For loop, the loop variable can be reserved outside of the derivation:

>>> x = 100 # this gets overwritten

>>> [x ** 3 for x in Range (5)]

[0, 1, 8, 27, 64]

>>> x # the final value for weight (5)

4

5.2 DEL statement

There is a way to remove the element of the specified index from the list: DEL statement. This method can also delete the slice from the linked list (before we assign an empty list to the slice). E.g:

>>> a = [-1, 1, 66.6, 333, 333, 1234.5]

>>> DEL A [0]

>>> a

[1, 66.6, 333, 333, 1234.5]

>>> DEL A [2: 4]

>>> a

[1, 66.6, 1234.5] DEL can also be used to delete the entire variable:

>>> DEL A

Thereafter, the name will then be an error (at least to give it another value). Later we will also find other usages of DEL.

5.3 Topology (TUPLES) and sequences (SEQUENCES)

We know that there are many universal properties such as indexes and slice operations. They are two kinds of sequence types. Because Python is a language inactivating, other sequence types can also be added, here there is another standard sequence type: topology.

A topology consists of several comma-separated values, for example:

>>> T = 12345, 54321, 'Hello!'

>>> T [0]

12345

>>> T

(12345, 54321, 'Hello!')

>>> # tPLES May Be Nested:

... u = t, (1, 2, 3, 4, 5)

>>> U

((12345, 54321, 'Hello!'), (1, 2, 3, 4, 5)))

As you can see, the topology is always in the output, so that the nested structure is properly expressed. There may be or without parentheses when entering, but often brackets are necessary (if the topology is part of a larger expression).

There are many uses in topology. For example, (x, y) coordinate points, employee records in the database, and more. The topology is like a string, which cannot be changed: a separate element that cannot give the topology (although you can simulate by joining and slice). It is also possible to create a topology, such as a chain list by including a variable object.

A special problem is to construct a topology containing zero or one element: In order to adapt to this situation, there are some additional changes on the grammar. A pair of air parentheses can create a null topology; to create a single element topology can be followed by a comma behind the value (not enough in parentheses). Ugly, but effective. E.g:

>>> EMPTY = ()

>>> Singleton = 'Hello', # <- Note Trailing CommA

>>> LEN (EMPTY)

0

>>> LEN (Singleton)

1

>>> Singleton

('Hello',)

The statement T = 12345, 54321, 'Hello!' Is an example of a topological package: values ​​12345, 54321, and 'Hello!' Are encapsulated into the topology. Its reverse operation may be like this:

>>> x, y, z = t

This call is called a sequence unpacking. The sequence unpacking requires the number of variables on the left to the same number of elements of the sequence. Note that variable parameters (Multiple Assignment

) Is actually just a combination of topology packages and sequence unpacking!

Here is a little asymmetry: Package multi-parameters typically create a topology, and the unpacking operation can act on any sequence.

5.4 Dictionary (Dictionaries)

Another very useful Python built-in data type is Dictionaries. Dictionary may be called "federated memory" (`) (`) (`)" (`)" in some languages ​​(`) (`). The sequence is indexed in a continuous integer, in connection with this, the dictionary is indexed by keywords, and the keyword can be arbitrarily non-variable type, usually using a string or value. If only strings and numbers are included in the topology, it can be used as a keyword, and if it directly or indirectly contains variable objects, it cannot be used as a keyword. You cannot use a chain list because the linked list can be used to instantly change with their APPEND () and Extend () methods, or by searching or by retrieving variables. The best way to understand the dictionary is to see it as unordered keyword: Value (key: value pairs) collection, keywords must be different (within the same dictionary). A pair of braces create an empty dictionary: {}. When the initialized chain table, place a comma-separated keyword in the braces: value pair, this is also the way the dictionary is output.

The main operation of the dictionary is stored and paid according to keywords. You can also use DEL to delete keywords: value pair. If you store the value with a keyword already existing, the value assigned to the keyword before it will be forgotten. Trying to draw a read value from a non-existent keyword can cause an error.

The keys () method of the dictionary returns a list of all keywords, which is uncertaintable (if you need it ordered, you can only call the sort () method of the keyword list. Use the HAS_KEY () method of the dictionary to check if there is a certain keyword in the dictionary.

This is a small example of a dictionary application:

>>> Tel = {'Jack': 4098, 'Sape': 4139}

>>> Tel ['Guido'] = 4127

>>> Tel

{'Sape': 4139, 'Guido': 4127, 'Jack': 4098}

>>> TEL ['Jack']

4098

>>> DEL TEL ['SAPE']

>>> Tel ['Irv'] = 4127

>>> Tel

{'Guido': 4127, 'IRV': 4127, 'Jack': 4098}

>>> TEL.KEYS ()

['Guido', 'IRV', 'Jack']

>>> Tel.has_Key ('Guido')

True

The dictionary can be configured directly from the dictionary in the linked list. Keyword-Value For from a mode, you can use a chain to derive a simple express keyword-value chain list.

>>> DICT ([('Sape', 4139), ('Guido', 4127), ('Jack', 4098)])

{'SAPE': 4139, 'Jack': 4098, 'Guido': 4127}

>>> DICT ([(x, x ** 2) for x in vec] # ue l l omen

{2: 4, 4: 16, 6: 36} 5.5 Cycling Skills

When cycling in a dictionary, the keywords and corresponding values ​​can be interpreted simultaneously with the items () method.

>>> Knights = {'gallahad': 'The pure', 'Robin': 'The Brave'}

>>> fork, v in knights.Items ():

... Print K, V

...

Gallahad the pure

Robin the BRAVE

When cycles in the sequence, the index position and corresponding value can be obtained simultaneously using the enumerate () function.

>>> for i, v in enumerate (['tic', 'tac', 'toe']):

... Print I, V

...

0 TIC

1 TAC

2 TOE

At the same time, two or more sequences can be circulated, and it can be interpreted using ZIP ().

>>> Questions = ['Name', 'Quest', 'Favorite Color']

>>> Answers = ['Lancelot', 'The Holy Grail', 'Blue']

>>> for q, a in zip (qustions, answers):

... Print 'What is your% s? IT IS% s.'% (Q, A)

...

What is your name? It is lancelot.

What is your quothesed? It is the Holy Grail.

What is your favorite color? It is blue.

5.6 In-depth conditions control

The conditions for the While and IF statements include an operator than the comparison.

In and NOT comparison operator review nuclear values ​​are within one interval. The operator IS and IS NOT compare whether the two objects are the same; this is only related to variable objects such as a linked list. All comparison operators have the same priority, lower than all numerical operations.

The comparison operation can be passed. For example, a

The comparison operation can be combined by logical operators and OR, and the results of the comparison can be retrieved with NOT. The priority of these operators is lower than the comparison operator, in them, NOT has the highest priority, the OR is the lowest, so A and not b or C is equal to (a and (not b)) or C. Of course, the expression can be represented by a desired manner.

Logical operators and OR are also referred to as short-circuit operators: their parameters are resolved from left to right, once the result is determined to stop. For example, if A and C are true and B is false, A and b and c will not parse C. When a normal non-logic value is actually, the return value of the short circuit operator is usually the last variable.

The return value of the comparison or other logical expression can be assigned to one variable, for example:

>>> String1, String2, String3 = ',' Trondheim ',' Hammer Dance '

>>> Non_null = String1 or string2 or string3

>>> Non_NULL

'Trondheim'

It should be noted that Python is different from C, and the internal expression cannot be assigned. C programmers often complain, but it avoids errors that have been used in the C program: I want to misuse = operator when == in the parsing. 5.7 Compare sequences and other types

Sequence objects can be compared to other objects of the same type. The comparison operation is performed in the words: first compare the first two elements, if the difference determines the result of the comparison; if the same, the two elements are compared, so that all sequences are completed. Comparison. If the two elements themselves are the same type of sequence, the recursive words are compared. If all children of the two sequences are equal, they will consider the sequence equal. If a sequence is the initial subsequence of another sequence, a shorter sequence is less than one. The character of the string is in order of the single-character ASCII order. Here are some examples of comparison between the same type of sequence:

(1, 2, 3) <(1, 2, 4)

[1, 2, 3] <[1, 2, 4]

'ABC' <'c' <'Pascal' <'Python'

(1, 2, 3, 4) <(1, 2, 4)

(1, 2) <(1, 2, -1)

(1, 2, 3) == (1.0, 2.0, 3.0)

(1, 2, ('AA', 'AB')) <(1, 2, ('ABC', 'A'), 4)

It should be noted that different types of objects are legal. The output result is determined rather than arbitrary: Types are sorted by their name. Thus, a linked list is always less than a string (String), and a string is always less than one topology (TUPLE), and the like. When the numerical type is compared, the data type is unified, so 0 is equal to 0.0, and so on. 5.1

Comment

... etc .5.1

Comparison rules for different types of objects do not depend this, they may

The subsequent version of the Python language changes.

Chapter directory

6.1 In-depth module

6.1.1 Module Search Path 6.1.2 "Compile" Python File 6.2 Standard Module 6.3 DIR () Function 6.4 Pack

6.4.1 Importing all information from the package (Importing * from a package) 6.4.2 Built-in bag (intra-package) Reference 6.4.3 Package in multiple paths

6. Module

If you exit the Python interpreter re-enter, all definitions (variables and functions) previously created are all lost. Therefore, if you want to write some long-term saved programs, it is best to use a text editor to write a program, and the saved file input interpreter. We call it a script. The program becomes longer, you might separate it into several files for your convenience maintenance. You may also want to use a commonly used function in several programs, but don't want to copy its definition to every program.

To support these needs, Python provides a method to get definitions from the file, use in an interactive instance of the script or interpreter. Such files are referred to as an instance; the definition in the module can be imported into another module or main module (the variables that can be called in the most advanced variables when the script is executed, and is in the calculator mode)

The module is a file including Python definitions and declarations. The file name is the module name plus .py suffix. The module name of the module (as a string) can be obtained by the global variable __name__. For example, you can create a file called Fibo.py in the current directory with your own file editor, enter the following: # Fibonacci NumBers Module

DEF FIB (N): # Write Fibonacci Series Up to N

A, b = 0, 1

While B

Print B,

A, B = B, A B

DEF FIB2 (N): # Return Fibonacci Series Up to N

Result = []

A, b = 0, 1

While B

Result.Append (b)

A, B = B, A B

Return RESULT

Now enter the Python interpreter to import this module with the following command:

>>> IMPORT FIBO

Don't import the functions in the FIBO into the current semantic table directly; it just introduces the module name FIBO. You can access this function as follows by the module name:

>>> 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 want to call a function directly, you can usually give it a local name:

>>> FIB = FIBO.FIB

>>> FIB (500)

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

6.1 In-depth module

The module can include execution statements like a function definition. These statements are usually used for initialization modules. They only execute once when the module is first imported. 6.1

The global semantic table corresponding to all functions in the defined module, each module has its own private language. Therefore, module authors can use some global variables in the module without incorrectly cause errors due to the global variables of the user. On the other hand, if you make sure you need this, you can get the global variables in the module like the function in the module, such as: modname.ItemName.

Modules can import (import) other modules. All IMPORT statements are all in the module (or script, etc.), but this is not necessary. The imported module is named in the global semantic table of this module.

One variant of the IMPORT statement is imported from the semantic table named this module directly from the imported module. E.g:

>>> from FIBO IMPORT FIB, FIB2

>>> FIB (500)

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

This will not import module names from the LAN (for example, FIBO is not defined).

There is also a variant to import all naming from the module definition:

>>> from FIBO IMPORT *

>>> FIB (500)

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

This can import all named in addition to the underline (_).

6.1.1 Module Search Path

When you import a module called a spam, the interpreter first searches for files named spam.py in the current directory, then searches in the directory list of environment variable pythonpath, and then the path list in the environment variable PATH. If PythonPath is not set, or if the file is not found, then search for the installation directory, in UNIX, usually.: / Usr / local / lib / python. In fact, the interpreter is specified by the path directory search module specified by the Sys.Path variable, which is initialized, and the input script (or the current directory), the PathPath, and the installation directory are included when the variable is initialized. This allows the Python program (the original, programs; I guess should be "programer", programmer-translator) to learn how to modify or replace the module search directory. It should be noted that these scripts should not be renamed with the standard module in these directorys, so these scripts should not be renamed, otherwise Python will attempt to load these scripts as a module when importing modules. This usually triggers an error. See Section 6.2 "Standard Modules" for more information.

6.1.2 "Compile" Python File

For short programs that reference a large number of standard modules, there is an important way to improve startup speed. If there is a file called spam.pyc in the spam.py directory, it is considered a pre-"compilation" of the SPAM module (` `Byte-compiled '', binary compilation) version. This version of the spam.py for creating spam.pyc is recorded in the spam.pyc file, if both do not match, .pyc files are ignored.

Usually you don't need to do anything for creating a spam.pyc file. Once spam.py successfully compiles, try to compile the corresponding version of spam.pyc. If there is any reason, the write is unsuccessful, and the returned spam.pyc file will be considered invalid, and then it is ignored. The content of the spam.pyc file is independent of the platform, so the Python module directory can be shared between the machines of different architectures.

Some advanced techniques:

When calling the Python interpreter with the -o parameter, an optimized code is generated and saved in the .pyo file. The general optimizer does not help; it just deletes an assertion statement. With -o parameters, all code will be optimized; .pyc file is ignored, the .py file is compiled as an optimized code. Passing two -O parameters (-OO) to the Python interpreter perform full optimized binary optimization compilation, which occasionally generates erroneous programs. Currently, the compressed .pyo file is only removed from the binary code, the __doc__ string is removed from the binary code. Because some programs depend on the availability of these variables, you should only use this option only in confirmation. Programs from .pyc files or .pyo files will not be faster than from .py files; .pyc or .pyo file is just faster when they load. When you run the script through the script, you will not create a .pyc or .pyo file for binary code for this script. Of course, move the main code of the script into a module, then import this module with a small deconstruction script, you can increase the start speed of the script. You can also specify a .pyc or dry .pyo file directly in the command line. For the same module (here the routine spam - translator), there can be only spam.pyc files (or spam.pyo, when using the -o parameter) without a spam.py file. This can package the Python code library that is compared to the reverse engineering. The CompialAll module can create a .pyc file for all modules in the specified directory (or create a .pyo file using the -o parameter). 6.2 Standard Module

Python has a standard module library and publishes a separate document called the Python Library Reference Manual (hereinafter referred to as "Library Reference Manual"). There are some modules to be placed in the interpreter, and the access interface of these operations is not part of the language kernel, but has been built into the interpreter. This is not only to improve efficiency, but also to provide an interface to an operating system such as system calls. This type of module collection is a configuration option that is dependent on the underlying platform. For example, the AMOEBA module only provides support for the AMOEBA native system. There is a specific module worth noting: SYS, this module is built into all Python interpreters. Variables Sys.ps1 and Sys.ps2 define the main prompt and Self-help prompt string:

>>> IMPORT SYS

>>> SYS.PS1

'>>>'

>>> SYS.PS2

'...'

>>> SYS.PS1 = 'C>'

C> Print 'Yuck!'

Yuck!

C>

These two variables are only meaningful in the interaction mode of the interpreter (herein, the original: these TWO VARIABLES ARE ONLY DEFINED IF The Interpreter is in Interactive Mode).

The variable sys.path is a list of strings for the interpreter module search path. It is initialized by environment variables pythonpath. If PythonPath is not within, it is initialized by the built-in default value. You can modify it with standard and string:

>>> IMPORT SYS

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

6.3 DIR () function

Built-in function DIR () is used to search for module definition by module name, which returns a list of storage lists:

>>> Import Fibo, SYS

>>> DIR (FIBO)

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

>>> DIR (SYS)

['__displayhook__', '__doc__', '__exceptHOK__', '__name__', '__stderr__',

'__stdin__', '__stdout__', '_getframe', 'API_Version', 'Argv',

'Builtin_Module_names', 'Byteorder', 'CallStats', 'Copyright',

'DisplayHook', 'Exc_clear', 'EXC_INFO', 'EXC_TYPE', 'EXCEPTHOOK',

'exec_prefix', 'executable', 'exit', 'getDefaultencoding', 'getDlopenflags',

'getRecursionLimit', 'getRefcount', 'HEXVERSION', 'Maxint', 'Maxunicode',

'meta_path', 'Modules', 'Path', 'Path_Hooks', 'Path_Importer_Cache',

'Platform', 'prefix', 'ps1', 'ps2', 'setCheckinterval', 'setdlopenflags',

'setprofile', 'setRecursionLimit', 'settrace', 'stderr', 'stdin', 'stdout',

'Version', 'Version_INFO', 'WarnOptions']

When there is no parameter call, the DIR () function returns the name of your current definition:

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

>>> Import Fibo, SYS

>>> FIB = FIBO.FIB

>>> DIR ()

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

You should list all types of names: variables, modules, functions, etc.:

DIR () does not list built-in functions and variable names. If you want to list this, they define them in standard modules __buildin__:

>>> IMPORT __BUILTIN__

>>> DIR (__ builtin__)

['ARITHMETICERROR', 'Assertionerror', 'AttributeError',

'DepRecationWarning', 'EOFERROR', 'Ellipsses', 'Environmenterror', 'Exception', 'False', 'FloatingPointError', 'Ioerror', 'Importerror',

'IndentationError', 'IndexError', 'Keyerror', 'KeyboardInterrupt',

'Lookuperror', 'MemoryError', 'NameError', 'None', 'Notimplement',

'NotimplementError', 'Osterror', 'OverflowError', 'OverflowWarning',

'PendingDepRecationWarning', 'ReferenceError',

'RuntimeError', 'RuntimeWarning', 'Standarderror', 'StopItemization',

'Syntaxerror', 'syntaxwarning', 'systemerror', 'systemExit', 'Taberror',

'True', 'TypeError', 'UnboundLocalerror', 'Unicodeerror', 'UserWarning',

'ValueError', 'Warning', 'ZerodivisionError', '__debug__', '__doc__',

'__import__', '__name__', 'ABS', 'Apply', 'Bool', 'Buffer',

'Callable', 'CHR', 'ClassMethod', 'CMP', 'COERCE', 'Compile', 'Complex',

'Copyright', 'Credits', 'DELATTR', 'DICT', 'DIR', 'Divmod',

'Enumerate', 'Eval', 'Execfile', 'Exit', 'File', 'Filter', 'Float',

'getattr', 'globals', 'Hasattr', 'Hash', 'Help', 'HEX', 'ID',

'INPUT', 'INT', 'INTERN', 'Isinstance', 'ISSUBCLASS', 'ITER',

'LEN', 'LICENSE', 'List', 'Locals',' LONG ',' MAP ',' MAX ',' MIN ',' Object ',' Oct ',' Open ',' ORD ',' POW ',' Property ',' Quit ',

'Range', 'Raw_INPUT', 'Reduce', 'Reload', 'Repr', 'Round',

'setttr', 'SLICE', 'StaticMethod', 'Str', 'String', 'Sum', 'Super',

'Tuple', 'Type', 'Unichr', 'Unicode', 'Vars', 'Xrange', 'Zip']

6.4 pack

The package is usually used with a structured module with a "dot module name" namespace. For example, a module named A.B represents a sub-module named "B" in a package called "A". As used as a module to save different module architectures to avoid mutual conflicts between global variables, using dot module names to save different type library architectures like NUNPY or PYTHON IMAGING LIBRARY to avoid naming conflicts between modules.

Suppose you want to design a module set (a "package") to unify the sound files and sound data. There are several different sound formats (usually by their extensions, for example: .wav, .aiff, .au), so in order to convert between different types of file formats, you need to maintain a growing package set. Maybe you also want to do a lot of different operations for sound data (such as mixing, add echo, application balancing function, create an artificial effect), so you have to join an infinite stream module to perform these operations. Your package may be this look (grouped by a graded file system):

Sound / Top-Level Package

__init__.py Initialize The Sound Package

Formats / Subpackage for File Format Conversions

__init__.py

WAVRead.py

WAVWRITE.PY

AIFFRead.py

AIFFWRITE.PY

Auread.py

Auwrite.py

...

Effects / Subpackage for Sound Effects

__init__.py

echo.py

Surround.py

REVERSE.PY

...

Filters / Subpackage for Filters

__init__.py

Equalizer.py

vocoder.py

Karaoke.py

...

When the module is imported, Python searches the subdirectory of the storage package via the directory list in sys.path.

There must be a __init__.py file existence to make Python as a package as the directory; this is to prevent some directories from using the general name such as "String" without intending to overwrite in the subsequent module search path. The correct module. In the simplest case, __ init__.py can just be an empty file, but it may also contain the initialization code of the package, or set the __all__ variable, and will have a related introduction. The package users can import legitimate modules from the package, for example:

Import snound.effects.echo

This is imported into the Sound.effects.echo submodule. It must be referenced by a complete name.

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

There is a way you select when importing the package:

From Sound.effects Import Echo

This loads the ECHO sub-module and allows it to be used without a packet prefix, so it can call as follows:

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

There is also another variant for direct import functions or variables:

From Sound.effects.echo Import Echofilter

This will then load the Echo submodule again, but this can directly call its echofilter () function:

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

It should be noted that when importing the package using the from package import item, this child (item) can be a submodule (or a sub-package) in the package, or other named function, a function, class defined in the package. Or variables. The import statement first checks if there is this child in the package, if not, it assumes this is a module and try loading it. If it does not find it, it will trigger an ImportError exception.

Instead, when using syntax like Import Item.subitem.SubSubItem, these subtries must be packets, and the final child can be package or module, but cannot be class, functions, or variables defined in the previous subkey.

6.4.1 Import all information from the package (Importing * from a package)

So what happens when the user wrote from from Sound.effects IMPORT *? Ideally, always want to find all the submodules in the package in the file system, and then import them. Unfortunately, this operation is not very good on the Mac and Windows platform, and these file systems are not sensitive! There is no way on these platforms to ensure that a file called Echo.py should be imported as a module Echo, Echo or Echo. (For example, Windows 95 has an annoying habit, which will display all filenames as the case of the first letter.) The DOS 8 3 file name restrictions bring another interesting question to the long file name module.

The only solution for the author of the package is to provide a clear package index. The import statement is converted as follows: When you perform from packae import *, if the __init__.py code in the package defines a linked list named __all__, it will be imported according to the module name given in the list. The new version of the package is published when the author can update this list. If the package is imported into all modules in their packages when Import *, it may also decide that it does not support it (import *). For example, Sounds / Effects / __ init__.py This file may include the following code: __ all__ = ["echo", "surround", "reverse"]

This means that the from snound.effects import * statement imports the above three named submodules from the Sound package.

If you don't define __all__, from snound.effects import * statement does not import all submodules from the Sound.effects package. Effects imports to the current namespace, can only be determined to import the Sound.effects package (initialization code that may run __init__.py) and all namings defined in the package will be imported. This imports each name (and explicitly imported sub-module) from __init__.py. It also includes a sub-module that is explicitly imported from the package, considering the following code:

Import snound.effects.echo

Import snound.effects.surround

From Sound.effects Import *

In this example, the Echo and the Surround module import current namespace because they have defined in the Sound.effects package when performing the from ... Import statement (also works like __all__).

It should be noted that habits do not advocate all modules from a package or module to import all modules, as this usually means that readability will be poor. However, doing this in an interactive session can reduce input, and the confirmed module is designed to only export the portion named in the determined mode.

Remember, from package import specific_submodule has no error! In fact, this is a recommended write method unless the imported module needs to use the same name sub-module in other packages.

6.4.2 Built-in package (intra-package)

The sub-module often needs to be referenced to each other. For example, the Surround module may reference the ECHO module. In fact, such reference is so common, so that the import statement will first search the package inside, and then the standard module search path. Therefore, Surround Module can simply call import echo or from echo import echofilter. If you do not find the module to import in the current package, the import statement looks for a top module in accordance with the specified name.

If a sub-package structure is used in the package (like the Sound Pack in the example), there is no convenience method that references the submodule from the adjacent package - the full name of the sub-package must be used. For example, if the Sound.Filters.vocoder package needs to use the Echosa module in the Sound.effects package, it can use from Sound.effects Import Echo.

6.4.3 Package in multiple paths

Package supports another special variable, __path__. This variable initializes a list of directory names before the __init__.py file code is executed. This variable can be modified, which acts on the search function of the subcaps and modules in the package. This feature can be used to expand module sets in the package, but it is not commonly used.

FootNotes

... Somewhere.6.1

In fact, the function definition is both "declaration" and "executable"; the actuator is imported by the function in the global semantic table of the module. (

In Fact Function Definitions Are Are `Executed '; The Execution Enters The Function Name in The Module's Global Symbol Table.)

Chapter directory

7.1 Design Output Format 7.2 Read and write

7.2.1 File Object (File Object) Method 7.2.2 Pickle Module

7. Enter and output

There are several ways to express the output of the program; the data can be printed with readable structures, or it can be written for later use. This chapter will discuss several feasible practices.

7.1 Design Output Format

We have two large-phase migration methods: expression statements and print statements. (The third visit is a wite () method using the file object, the standard file output can be referred to sys.stdout. Details See the library reference manual.)

Maybe you often want to make some more complicated control over the output format than simple print space division. There are two ways to format the output. The first is to control the entire string of the entire string, you can create any output form you want using the character slice and join operation. Standard module String includes some operations that fill the string into the given column, which is useful. Then we will discuss this part. The second method is to use the% operator as its left parameter in a string. The% operator interprets the left parameter as a format string similar to the sprintf () style, and acts on the right parameter, returns a formatted string from this operation.

Of course, there is a problem, how to convert (different) values ​​into strings? Fortunately, Python always passes any value into the REPR () or STR () function, and is converted to a string. Relative to the quotation marks ('') equivalent to REPR (), but does not promote this.

Function STR () is used to convert values ​​to a form suitable for man reading, while REPR () is converted to an interpreter read (if there is no equivalent syntax, the syntaxerror exception will occur) A object is not suitable for people. If you read the explanation, STR () will return to the REPR () equivalent value. Many types, such as values ​​or linked lists, structures such as a dictionary, have a unified interpretation of each function. Strings and floating point numbers have a unique interpretation.

Here are some examples:

>>> s = 'Hello, World.'

>>> STR (s)

'Hello, World.'

>>> REPR (S)

"'Hello, World.'"

>>> Str (0.1)

'0.1'

>>> REPR (0.1)

'0.10000000000000001'

>>> x = 10 * 3.25

>>> Y = 200 * 200

>>> s = 'the value of x is' repr (x) ', and y is' repr (y) '... >>> Print S

The value of x is 32.5, and y is 40000 ...

>>> # The repr () of a string add string quotes and backslashes:

... Hello = 'Hello, World / N'

>>> Hellos = Repr (Hello)

>>> Print Hellos

'Hello, World / N'

>>> # The argument to repr () May Be Any Python Object:

... REPR ((x, y, ('spam', 'eggs'))))))))

"(32.5, 40000, ('spam', 'eggs'))"

>>> # Reverse Quotes Are Convenient in Interactive Sessions:

... `x, y, ('spam', 'eggs')`

"(32.5, 40000, ('spam', 'eggs'))"

The following two methods can output the square and cube:

>>> Import String

>>> for x in Range (1, 11):

... Print String.rjust (Repr (x), 2), String.rjust (REPR (x * x), 3),

... # Note Trailing Comma on Previous Line

... Print String.rjust (REPR (x * x * x), 4)

...

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

>>> for x in Range (1,11):

... Print '% 2D% 3D% 4D'% (x, x * x, x * x * x)

...

1 1 1

2 4 8

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

(Need to note that there is a space between the two columns when using the Print method: it always adds a space between the parameters.)

The above is a String.rjust () function demonstration, which outputs the string to a column and fill the space to the left side to align it. Similar functions include string.ljust () and String.center (). These functions are only output new strings and do not change anything. If the string of the output is too long, they will not truncate it, but it will output it, which will make your output format confuse, but always over another selection (truncated string), because it will generate errors Output value. (If you really need to truncate it, you can use a slice operation, for example: "String.ljust (x, n) [0: n]".) There is also a function, string.zfill () it is used to the value of the string Express the left to populate 0. This function can correctly understand the corrective number:

>>> Import String

>>> String.ZFILL ('12 ', 5)

'00012'

>>> String.ZFILL ('- 3.14', 7)

'-003.14'

>>> String.ZFILL ('3.14159265359, 5)

'3.14159265359'

You can use the% operator as follows:

>>> Import Math

>>> Print 'The value of pi is approximately% 5.3f.'% Math.pi

The value of pi is approximately 3.142.

If there is more than one string to format it, it is necessary to pass them into a tuple as the right value, as shown below:

>>> table = {'sjoerd': 4127, 'Jack': 4098, 'DCAB': 7678}

>>> for Name, Phone in Table.Items ():

... Print '% -10s ==>% 10D'% (Name, Phone)

...

Jack ==> 4098

DCAB ==> 7678

Sjoerd ==> 4127

Most types of formatting operations require you to get into the appropriate type, but if you don't define an exception, there will be no one from the kernel. (However, if you don't you get an exception, not a core dump) Use the% S format to be more easily: If the corresponding parameter is not a string, it converts the built-in STR () function into a string. Python supports the transmission of width or accuracy with * as an isolated (integer) parameter. Python does not support C's% N and% P operators.

If you can reference the variable name to format by point, you can generate a format string that meets the real length and does not generate intervals. This effect can be implemented by using the form% (Name) structure:

>>> Table = {'Sjoerd': 4127, 'Jack': 4098, 'DCAB': 8637678}

>>> Print 'Jack:% (JACK) D; Sjoerd:% (SJOERD) D; DCAB:% (DCAB) D'% TableJack: 4098; Sjoerd: 4127; DCAB: 8637678

This trick is very useful when used in combination with the new built-in function Vars (), which returns a dictionary containing all local variables.

7.2 read and write files

Open () Returns a file object, usual usage requires two parameters: "Open (filename, Mode)".

>>> f = Open ('/ tmp / workfile', 'w')

>>> Print f

The first parameter is a string that identifies the file name. The second parameter is a string consisting of limited letters, which describes how the file will be used. The optional mode is: 'r', this option makes the file read only; 'W', this option makes the file only writes (for the same name file, this action makes the original file overwrites); 'a', this option is appended Way open files; 'R ', this option opens files in reading and writing; if not specified, the default is 'r' mode.

On Windows and Macintosh platforms, 'B' mode opens files in binary, so there may be a combination of 'RB', 'WB', 'R B', etc.. The text file and binary files are different from the two-write files on the Windows platform, and the row will be automatically added. This background operation does not have any problems with the text file, but it is destroyed when it operates JPEG or EXE. When operating these files, you must remember to open in binary mode. (Need to note is the text mode on the MAECTIONTOSH platform depends on the underlying C library it uses.

7.2.1 Method of File Object

The examples in this section are default file object f.

To read the contents of the file, you need to call F.Read (size), which reads several quantities and returns its content as a string, and the string length is specified by the value size. If you do not specify size or a negative number, you will read and return the entire file. An issue will occur when the file size is twice the current machine memory. Under normal circumstances, the data is read and returned as much as possible. If it is at the end of the file, F.Read () will return an empty string ("").

>>> F.Read ()

'This is the entire file./n'

>>> F.Read ()

'' '

F.Readline () reads a single line from the file, the string will automatically add a newline, only when the final row does not have the final line, this operation will be ignored. If the return value will not be confused, if IF f.readline () returns an empty string, then it is said to arrive at the end of the file. If it is an empty line, it will be described as '/ n', one only Contains a string of a wrap.

>>> f.readline ()

'This is the first line of the file./n'

>>> f.readline ()

'Second Line of the file / n'

>>> f.readline () ''

F.ReadLines () Returns a list that contains all the data lines in the file. If a Sizehint parameter is given, the number of bits of more than one line is read, and the row list is returned. This feature is often used to efficiently read large row files to avoid reading the entire file into memory. This operation only returns a complete line.

>>> f.readlines ()

['This is the first line of the file./n', 'second line of the file / n']

F.Write (string) writes the String content into the file and returns None.

>>> F.Write ('this is a test / n')

f.Tell () Returns an integer that represents the pointer position in the file object in the file, which is measured from the beginning to the number of bits at the pointer. You need to change the file object nuttelling, use "F.seek (offset, from_what)". The pointer moves OFFSET bits from the specified reference position in this operation, and the reference location is specified by the from_what parameter. The from_what value is 0 indicates that the initial starting from the file, 1 indicates that from the current file pointer position, 2 means starting from the end of the file. From_what can be ity, its default value is zero, starting from the file header.

>>> f = Open ('/ tmp / workfile', 'R ')

>>> F.Write ('0123456789abcdef')

>>> F.Seek (5) # Go to the 6th byte in the file

>>> F.Read (1)

'5'

>>> F.Seek (-3, 2) # Go to the 3rd byte before the end

>>> F.Read (1)

'd'

After the file is used, call f.close () to turn off the file, release the system resources that open the file. After calling f.close (), call the file object automatically triggers an error.

>>> f.close ()

>>> F.Read ()

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

ValueError: I / O Operation On Closed File

File objects There are still some uncommon additional methods, such as isatty () and truncate () in the library reference manual's full guide.

7.2.2 Pickle Module

We can read and write strings in the document. The value must be more than one fold, because the read () method will only return a string, and it should be transferred to the string.atoi () method, and the characters such as '123' can be converted to the corresponding value. However, when you need to save more complex data types, such as linches, dictionaries, classes, things will become more complicated.

Fortunately, users don't have to write and debug code that saves complex data types. Python provides a standard module called Pickle. This is an amazing module that can be used to express any Python objects (even some python code blocks (form)!) As a string, this process is called Pickling. Expressing the restructuring object from a string is called unpickling. Objects in the package can be stored in file or objects, or can be transmitted between remote machines over the network. If you have an object X, a file object f that is written in a write mode, the simplest method of the package, only one line of code:

Pickle.dump (x, f)

If F is a file object that opens in read mode, you can reload this object:

x = pickle.load (f)

(If you don't want to write the packaged data into the file, there are some other changes available. For complete PICKLE documentation, please see the library reference manual).

Pickle is a standard method that stores the Python object for other programs or itself. Providing this group of techniques is a persistent object ("Persistent Object). Because the use of Pickle is very wide, many Python expansion authors are very note whether the new data types such as matrices are suitable for packaging and unpacking.

Subdirectory

8.1 Syntax Error 8.2 Exceptions 8.3 Processing Exceptions 8.4 Throwing Exceptions 8.5 User Custom Abnormal 8.6 Defining Cleaning Behavior

8. Error and exception

So far, there is no further talk about error messages, but in those examples you have tried, it may have been encountered. There are two errors in Python (at least): Syntax Errors and Exceptions.

8.1 Syntax error

Syntax errors, also known as parsing errors, may be the easiest to learn Python:

>>> While True Print 'Hello World'

FILE "", LINE 1, in?

While True Print 'Hello World'

^

SyntaxError: Invalid Syntax

The parser repeats the wrong line and displays a small arrow at the wrong position in the previous row. Error (at least detected) occurs at the point where the arrow is pointing. The error in the example is on the keyword print, because there is a colon (:) before it. At the same time, the file name and the line number will be displayed so you can know which script from the error comes from.

8.2 exception

Even when you have a fully correct statement, it is possible to do it when you try to execute it. The error detected in the program is called an exception, which usually does not lead to fatal problems, and you will soon learn how to control them in the Python program. Most exceptions will not be handled by the program, but to display an error message:

>>> 10 * (1/0)

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

ZerodivisionError: Integer Division or MODULO by Zero

>>> 4 SPAM * 3

TRACEBACK (MOST RECENT CALL LAST):

FILE "", line 1, in? Nameerror: name 'spam' is not defined

>>> '2' 2

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

TypeError: Cannot Concatenate 'Str' and 'Int' Objects

The last line of the error message indicates something wrong. Exceptions also have different types, and the exception type is displayed as part of the error message: the exceptions in the example are zero-era errors, named errors, and type errors. When printing an error message, the anomalous type is displayed as an exception's internal name. This is the case for all built-in abnormalities, but the user's custom exception is not necessarily (although this is a very useful agreement). The standard exception name is a built-in identifier (no keywords).

This line is a detailed description of this exception type, which means its content is dependent on an exception type.

The first half of the error message lists an abnormal position in the form of a stack. Source code rows are usually listed in the stack, however, the source code from the standard input will not be displayed.

The Python Library Reference Manual lists the built-in exceptions and their meaning.

8.3 processing exception

The specified exception can be processed by programming. The following example repeats the user to enter a value until the user enters a legal integer. However, this program allows the user to interrupt the program (using a method of supporting the Control-C or other operating system). It should be noted that the interrupt of the user will trigger a keyboardInterrupt exception.

>>> While True:

... TRY:

... x = int (Raw_Input ("" please enter a number: "))

... BREAK

... Except ValueError:

... Print "OOPS! That Was No Valid Number. Try Again ..."

...

The TRY statement works as follows:

First, execute the TRY clause (part between TRY and Except keywords). If there is no abnormality, the Except clause is ignored after the TRY sentence is executed. If an exception occurs during the execution of the Try clause, the rest of the subsept will be ignored. If the exception matches the exception type specified after the Except keyword, the corresponding ExcePT clause is performed, and other parts of the TRY clause is ignored. Then continue the code after the TRY statement. If an exception has occurred, there is no branch that matches it in the Except clause, it will pass to the previous TRY statement. If the corresponding processing statement is still not found, it becomes an unprocessed exception, the termination program is run, and the prompt information is displayed.

A TRY statement may contain multiple Except clauses, specifying different exceptions, respectively. At most, there will be only one branch is executed. The exception handler will only process an exception that occurred in the corresponding TRY clause, in the same TRY statement, the abnormality that occurs in other clauses is not processed. An Except clause can list multiple exception names in parentheses, for example:

... ExcePt (RuntimeError, TypeError, NameError):

... pass the last Except clause can omit an abnormal name, use it as a communication. Be careful to use this method, because it is likely to block the real program error, can't find it! It can also be used to print a row error message and then re-throw an exception (which can make the caller better process exception).

Import string, sys

TRY:

f = open ('myfile.txt')

s = f.readline ()

i = int (String.Strip (s))

Except Ioerror, (Errno, STRERROR):

Print "I / O Error (% S):% S"% (errno, strrror)

Except ValueError:

Print "Could Not Convert Data to An Integer."

Except:

Print "Unexpected Error:", sys.exc_info () [0]

Raise

The TRY ... Except statement can have an else clause that can only appear after all Except clauses. When the TRY is not thrown out, you need to perform some code, you can use this clause. E.g:

For arg in sys.argv [1:]:

TRY:

f = Open (arg, 'r')

Except Ioerror:

Print 'Cannot Open', Arg

Else:

Print Arg, 'HAS', LEN (F.Readlines ()), 'Lines'

f.close ()

Using the Else clause is better than adding a code in the TRY clause, because this avoids the exception thrown by Try ... Except unexpected interception that does not belong to those code they protected.

When an exception occurs, there may be an accessory value as an abnormal parameter. Whether this parameter exists, what type is dependent on an exception type.

After the exception name (list), a variable can also be specified for the Except clause. This variable is bound to an exception instance, which is stored in the parameter of Instance.Args. For convenience, the abnormal instance defines __getitem__ and __str__, so you can directly access the print parameters without having to reference .args.

>>> TRY:

... Raise Exception ('spam', 'eggs')

... Except Exception, INST:

... Print Type (INST) # The Exception Instance

... Print Inst.Args # arguments stored in .args

... Print Inst # __STR__ALLOWS ARGS to Printed Directly

... x, y = INST # __GETITEM__ALLOWS ARGS TO BE Unpacked Directly

... Print 'x =', X

... Print 'Y =', Y

...

('spam', 'eggs')

('spam', 'eggs')

X = spam

Y = Eggs

For unprocessed exceptions, if it has a parameter, it will be printed as the last part of the error message ("details"). Exception handle can do not allow the exception that occurs directly in the TRY clause, even in which the function is (or even indirect), an exception occurs, or can be processed. E.g:

>>> DEF this_fails ():

... x = 1/0

...

>>> TRY:

... this_fails ()

... Except ZerodiVisionerror, Detail:

... Print 'Handling Run-Time Error:', Detail

...

Handling Run-Time Error: Integer Division or MODULO

8.4 Throwing anomalies

When a specific exception has occurred, the programmer can force the abnormality with the RAISE statement. E.g:

>>> Raise NameError, 'Hithere'

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

Namerror: Hithere

The first parameter specifies the name of the abnormality thrown, the second specified parameters.

If you decide to throw an exception without dealing with it, the Raise statement allows you to quickly reap out the exception.

>>> TRY:

... Raise NameError, 'Hithere'

... Except NameError:

... Print 'An Exception Flew By!'

... raise

...

An Exception Flew By!

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 2, IN?

Namerror: Hithere

8.5 User Customization

You can name your own exception by creating a new exception type. Abnormal classes should usually be derived from the Exception class directly or indirectly, for example:

>>> Class MyError (Exception):

... DEF __INIT __ (Self, Value):

... Self.Value = Value

... DEF __STR __ (Self):

... Return Repr (Self.Value)

...

>>> TRY:

... raise myerror (2 * 2)

... EXCEPT MYERROR, E:

... Print 'My Exception Occurred, Value:', E.Value

...

MY Exception Occurred, Value: 4

>>> Raise MyError, 'OOPS!'

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 1, in?

__main __. myerror: 'OOPS!'

Anything in any other class can be defined in any other class, but usually in order to maintain a simple, only several attribute information are added to an exception handle extract. If you need to throw several different errors in a newly created module, a usual process is to define an exception base class for the module and then give a corresponding exception subclass for different error type. Class Error (Exception):

"" "Base Class for Exceptions in this module." ""

PASS

Class InputError (Error):

"" "Exception raised for errors in the input.

Attributes:

Expression - INPUT Expression in which the error occurre

Message - Explanation of the error

"" "

DEF __INIT __ (Self, Expression, Message):

Self.Expression = Expression

SELF.MESSAGE = Message

Class TransitionError (ERROR):

"" "Raised when an operation attempts a state transition That's Not

ALOWED.

Attributes:

Previous - State At Beginning Of Transition

Next - Attempted New State

Message - Explanation of why the specific Transition is not allowed

"" "

Def __init __ (self, previous, next, message):

Self.previous = previous

Self.next = Next

SELF.MESSAGE = Message

Similar to standard abnormalities, most abnormal namings end with "error".

Many standard modules have defined their own exceptions to report errors that may occur in the functions they define. For further information on the class, see Chapter 9, "Class".

8.6 Defining Cleaning Behavior

The TRY statement has another optional clause that defines the functions that must be performed in any case. E.g:

>>> TRY:

... Raise KeyboardInterrupt

... Finally:

... Print 'Goodbye, World!'

...

Goodbye, World!

TRACEBACK (MOST RECENT CALL LAST):

FILE "", LINE 2, IN?

KeyBoardInterrupt

The Finally clause will be executed regardless of the exception in the TRY clause. If an exception occurs, it will be reappeared after the finally clause is executed. The TRY clause will also perform the finally clause.

The code in the Finally clause is used to release external resources (such as files or network connections), regardless of whether these resources have been successfully utilized.

Several Except clauses or a finally clause can be used in the TRY statement, but both cannot coexist.

Translator: The text section of this Python guide is complete, thanks to Clover sister, SICKKID, Yin Weiming, face, 珂 and other friends give me help and support from the translation process. Special thanks to Python Guide 2.2 (http://python.cn/contents/python_tutorial/python-tutorial.html) author Li Dongfeng. In the last chapter, the terminology and other content have been revised and unified with reference to his translation, which greatly improves the work efficiency and the quality of this chapter. Chapter directory 9.1 Topic of the term 9.2 Python action domain and namespace 9.3 primary

9.3.1 Class Definition Syntax 9.3.2 Class Objects 9.3.3 Instance Objects 9.3.4 Method Objects 9.4 Some Description 9.5 Inheritance

9.5.1 Multiple Inheritance 9.6 Private Variables 9.7 Supplement 9.8 Anomaly is also a class 9.9 iterator 9.10 generator

9. Class Python joins the class mechanism as much as possible without adding new syntax and semantics. This mechanism is a mix of C and Python's Modula-3. The classes in Python do not create an absolute barrier between users and definitions, but depending on the user's consciousness, not "destroy definition". However, the most important function of the class mechanism is completely reserved. The class inheritance mechanism allows multiple inheritance, derived classes to override any method in the override base class, and the method of the same name in the base class can be invoked. Objects can contain any number of private members. In terms of C terms, all class members (including data members) are public, and all member functions are virtual (Virtual). In terms of modula-3, there is nothing in a simple manner in a member method (shorthands) can refer the member of the object: The method function needs to be first parameters as the reference object when defined, and it will hidden when calling Citing object. This forms a semantic introduction and rename. (This Provides Semantics for Importing and Renaming.) However, like C instead of MODULA-3, most of the built-in operators (algorithm operators, subscripts, etc.) with special syntax can be redefined for classes. 9.1 Topics of the terminology Since there is nothing about the generic term, I borrow some from SmallTalk and C (I prefer to use MODULA-3 because it is more close to Python than C , but I think there is not much reader. I heard it). I want to remind the reader, there is an object-oriented term trap, and the word "object" in Python does not necessarily spectrum instance. Not all types in Python are class: For example, the built-in data type is not, or even some external types such as files are not, this is similar to C and Modula-3, not like SmallTalk. However, all Python types have a bit of semantics: describing their most appropriate words are "objects". Objects are special, multiple names (in multiple scopes) can bind the same object. This is equivalent to alias in other languages. This is usually ignored in the first impression of Python, and it can also be very safe when using those non-variable basic types (values, strings, tuples). However, this semantics will have an impact when the Python code calls the dictionary, the variable object, and most of the types involving the program external entity (files, forms, etc.). This generic helps optimize the program because the alias behavior is similar to the pointer. For example, it is easy to pass an object because it only passes a pointer in behavior. If the function modifies an object passed through the parameter, the caller can receive changes - this requires two different parameter transfer mechanisms in Pascal. 9.2 Python Schemes and Namespace Before introducing the class, I first introduce some rules about the Python scope: the definition of the class is very cleverly uses namespace. To fully understand the knowledge, you need to understand the scope and name space. Working principle. In addition, all knowledge is very useful for any advanced Python programmers. We started from some definitions. Namespace is a mapping named object.

The current namespace is mainly implemented through the Python dictionary, but it is usually not concerned with specific implementation (unless it is considered), it may also change its implementation. There are some examples of namespaces: built-in naming (like ABS () ", and built-in exception names) set, local naming in the module in the module. Name. A genre set of objects in a sense is also a namespace. One important thing about namespace needs to be understood is that there is no contact in different namespaces, such as two different modules may define a function called "maximize" without confusion - users must The module is called to reference them. By the way, I am called any "." After Python is named attribute - for example, REAL in the expression z.Real is an attribute of object Z. Strictly speaking, the reference naming from the module is a reference property: In the expression modname.funcname, MODNAME is a module object, and FuncName is an attribute. Therefore, the properties of the module and the global naming in the module have direct mapping relationships: they share the same namespace! 9.1 The property can be read or written. In the latter case, the attribute can be assigned. You can do this: "MODNAME.THE_ANSWER = 42". The writable properties can also be deleted with the DEL statement. For example: "DEL MODNAME.THE_ANSWER" will delete the_answer attribute from the MODNAME object. Different namespaces are created at different times, there are different survival. The namespace containing the built-in named name is created when the Python interpreter is started, and will remain, not deleted. The global namespace of the module is created when the module definition is read, usually, the module namespace will always be saved to the interpreter exit. The statement that is executed by the interpreter at the highest layer, whether it is part of the __main__ module, whether it is from the script file or from an interactive input, so they also have their own namespace. (Built-in naming is also included in a module, it is called __builtin__.) When a function is called, a partial namespace is created, and the function is returned to throw an exception that does not process within the function. Delete. (In fact, it is more appropriate for forgetting. Of course, each recursive call has its own namespace. The scope refers to the namespace that the Python program can access directly. "Direct Access" here means that additional modifiers do not need to be added when naming in the namespace. Although the scope is static definition, they are dynamic during use. At least three namespaces can be accessed directly, and the domain containing local named domain is in the most inside, first searched; secondly sector, the mid-layer scope, here contains the same level Function; Finally Search the outermost scope, it contains a built-in naming. If a naming declaration is globally, all assignments and references are directly directed to the intermediate scope of the global named. In addition, variables of all inner layer scavenging domains accessed from the outside are read-only. From the text sense, the local scope references the current function name. In addition to the function, the local scope is referenced to the same namespace with the global use domain: module namespace. Class definitions are also another namespace in the local scope. The scope is determined in the source program: a global scope defined in a module is the namespace of the module, not the alias of the function being defined or called, understanding this is very important.

On the other hand, the named actual search process is dynamic. It is determined at runtime - however, the Python language is constantly evolving. It may be determined when it is static "Compilation", so don't depend on dynamic analysis! (In fact, local variables are already static.) One of Python is that its assignment operation is always in the proderation domain. Assignment does not copy data - just binds naming to the object. This is also the same: "DEL X" is just deleting a namex from the namespace of the local scope. In fact, all the newly named operations act on the local scope. In particular, the IMPORT statement and the function set will bind the module name or function to the local scope. (You can use the Global statement to introduce variables to global scope.) 9.3 The primary knowledge class introduces a new syntax, three new object types, and some new semantics. 9.3.1 Class definition syntax The simplest class definition form is as follows: Class ClassName:

.

.

.

definition is like a function definition (DEF statement), you must implement it first. (You can of course put it into a branch of the IF statement, or a function of a function.) Access to the content of the class definition statement is usually the function definition, but other statements can be, sometimes it is useful - after we will Go back to discuss. The function definition in the class typically includes a special form of parameter list for method calls, and we discuss this later. When defining a class, create a new namespace, use it as a local scope - therefore, so the assignment of local variables is introduced into a new namespace. In particular, the function definition is bound to this. When the class definition is complete (normal exit), a class object is created. Basically, it is a packaging for the namespace created by class definitions; we learn more about the knowledge in the next section. The original local scope (that is introduced before the introduction of the introduction) is recovered, and the class object is bound to the class name definition header here (ClassName in the example). 9.3.2 Class object class object supports two operations: attribute references and instantiation. Attribute references use the same standard grammar as all attributes in Python: Obj.name. After class object creation, all namings in class namespaces are valid attribute names. So if the class definition is like this: Class Myclass:

"A Simple Example Class"

i = 12345

DEF F (Self):

Return 'Hello World' Then myclass.i and myclass.f are valid attribute references, which returns an integer and a method object, respectively. You can also assign a value for class properties, you can modify it by assigning values ​​to myclass.i. __doc__ is also a valid attribute, returning a class of document strings: "a Simple Example Class". Instantian use function symbols. As long as the class object is considered as a non-parameter function that returns a new class instance. For example, a new class instance is created over the previous class): x = myclass (), and assigns the object to the local variable x. This instantiation operation ("calls" a class object) to create an empty object. Many classes tend to create objects as initial states. Therefore, the class may define a special method called __init __ (), like this: DEF __INIT __ (Self):

Self.Data = [] Class defines the __init __ () method, the instantiation of the class automatically calls the __init __ () method for the newly created class instance. So in the following example, a new instance can be created: x = myclass () is of course, for elasticity, __init __ () method can have parameters. In fact, the parameter is passed to the instantiation of the class via __init __ (). For example: >>> Class Complex: ... DEF __INIT __ (Self, RealPart, Imagpart):

... Self.R = RealPart

... self.i = iMagpart

...

>>> X = Complex (3.0, -4.5)

>>> X.R, X.I

(3.0, -4.5) 9.3.3 Instance objects Now we can use instance objects? The unique operation of an instance object is the attribute reference. There are two valid attribute names. The first kind is called data attributes. This is equivalent to "instance variable" or "data member" in C in SmallTalk. Like local variables, data attributes do not require statements, they will generate when they use. For example, if x is a Myclass instance created in front, the following code will print 16 without any excess residue: x.counter = 1

While X.counter <10:

x.counter = x.counter * 2

Print X.counter

Del X.Counter The second specification attribute accepted by instance object is a method. The method is a function of an object. (In Python, the method is not limited to the class instance: Other types of objects can also have a method. For example, the list object has append, insert, remove, sort, however, here, unless otherwise specified, we mention Method Special Name of the Method Special Method Depending on Its Class. Follow the definitions, all (user-defined) function objects in the class corresponding to the method in its instance. So in our example, X..f is an effective method reference because myclass.f is a function. But X.i is not because myclass.i is a function. However, X.f and myclass.f are different - it is a method object, not a function object. 9.3.4 Method Object The method is to call directly: X.f () in our example, which will return string 'Hello World'. However, it is not necessary to call the method directly. X.f is a method object that can be called later. For example: xf = x.f

While True:

Print XF () will continue to print "Hello World". What happened when calling a method? You may notice that the previous marked variable is not referenced when calling X.f (), although a parameter is indicated in the F function definition. What happened to this parameter? In fact, if the parameters are missing in the function call, Python will throw an exception - even this parameter actually doesn't use ... In fact, you may have guessed the answer: the special method of the method is the first parameter of the example object as a function Pass it to the function. In our example, call X.f () is equivalent to myclass.f (x). Typically, a method of n parameters is called, which is equivalent to inserting the object's object into the front of the parameter list, and calls the corresponding function with this list. If you still don't understand how the method works, you can understand that its implementation may help. When the instance property of the non-data attribute is referenced, it will search it. If this name is confirmed as a valid function object class properties, instance objects and function objects are encapsulated into an abstract object: this is the method object. When calling method objects with a parameter list, it is renewed, constructed a new parameter list with an instance object and the original parameter list, and then the function object calls this new parameter list. 9.4 Some descriptions [Some content may need to be clear ...] The same name's data attribute overrides the method properties, in order to avoid possible naming conflicts - this may cause difficult BUG in large programs, it is best to name Avoid conflicts. Optional conventions include the first letter uppercase of the method, data attribute name prefix lowercase (possibly just a downline), or the method uses the verb and the data attribute uses noun. Data attributes can be referenced by methods, or they can be called by ordinary users (clients). In other words, the class cannot achieve a pure data type. In fact, there is no way in Python to force hidden data - all basically conventions. (Another method, Python's implementation is written in C, if necessary, can write Python extensions, fully hide the details, and control the access.) Customer should be careful to use data properties - customers may Since the data consistency maintained by the method is destroyed by the free modification of data attributes. It should be noted that customers only need to avoid naming conflicts, they can add data attributes to the instance without affecting the effectiveness of the method - once again emphasized, naming conventions can save a lot of trouble. There is no shortcut to reference data attributes (and other methods) from ways. I think this in fact adds the readability of the method: even if a rough browsing one method, there will be no chance to confuse local variables and instance variables. It is used to the first parameter of the method named Self. This is just a convention: For Python, SELF has no special meaning. (However, it should be noted that if you do not follow this agreement, other Python programmers will have inconveniences when reading your code, and some browsing programs are also developed here.) Any function object in class properties in class instances Both are defined as a method. It is not necessary to write a function definition code into a class definition, or you can assign a function object to one variable in the class. For example: # function defined Outside The Classdef F1 (Self, X, Y):

Return MIN (X, X Y)

Class C:

f = f1

DEF G (Self):

Return 'Hello World'

H = G Now f, g and h are attributes of class C, which are all function objects, so they are all methods of C instance - h stringent equals G. It should be noted that this habit usually only confuses the program readers. The method of the SELF parameter can call other methods: Class Bag: DEF __INIT __ (Self):

Self.Data = []

DEF Add (Self, X):

Self.Data.Append (x)

Def AddTwice (Self, X):

Self.Add (x)

The Self.Add (X) method can reference global naming as reference to the normal function. The global scope associated with the method is a module that contains a class definition. (The class itself will never be used as a global scope!) Although there are very few reason to use global data in the method, there are many legitimate uses: First, the method can call the import global scope function. And methods, you can also call the classes and functions defined therein. Usually, classes containing this method will also be defined in this global scope. In the next section, we will understand what method to reference your own class! 9.5 Inherited Of course, if a language does not support inheritance, "class" does not make sense. Definitions are as follows: Class DerivedClassName: Class DerivedClassName:

.

.

.

NameclassName (the base class name in the example) must be defined in a scope with the derived class. In addition to the class, this is also useful in expressions. This is very useful when defining in another module: Class DerivedClassName: The execution process of derived class definitions is the same. When constructing a classic object, remember the base class. This is especially useful when parsing attributes: If the property is not found in the class, the base class is searched. If the base class is derived from the other class, this rule will be recursive. There is no special place for the instantiation of derived classes: DeriveDClassName () (derived class in the field) creates a new class instance. Method references parsed as follows: Search the corresponding class properties, select along the base class, if necessary, if the function object is found, it is legal. Detective classes may cover the methods of their base. Since the method is called when the method is called in the same object, the method of the base class is not privileged, and when the method of the base class calls the same base class, it may actually finally call the coverage method in the derived class. (For C programmers, all methods in Python are inherently false.) The coverage method in the derived class may be a re-renovation rather than a simple replacement base class. There is a simple way to call the base class directly, as long as the call: "BaseclassName.MethodName (Self, Arguments)". Sometimes this is also useful for customers. (It should be noted that only the base class can be used in the same global scope to define or import.) 9.5.1 Multi-inheritance of Python is equally limited to support multi-inheritance form. Multi-inherited class definitions are as follows: Class derivedClassName (base1, base2, base3):

.

.

.

The only semantics that need to be explained here are rules for parsing class properties. The order is depth priority, from left to right. Therefore, if an attribute is not found in DeriveDClassName (the derived class in the example), then the base1 is searched, then (recursively) searching its base class, if it is finally not found, search for Base2, and so on. (Some people think breresses - Search Base2 and Base3 before searching Base1, it looks more natural. However, if you have a naming conflict between Base1 and Base2, you need to understand this property is defined in BASE1 or In the base class of Base1. And the depth priority is not distinguished attribute inherits the self-base class or direct definition.) Obviously, the use of multiple inherits that will not be restricted will bring maintenance nightmare, because Python relies on the agreement to avoid naming conflicts. Inheriting a very famous question is that the two base classes that derive inheritance are inherited from the same base class. It is still unclear that this is meaningful in semantics, but it is easy to think of this consequence (instance has a separate "instance variable" or data attribute replica acting on public base class.) 9.6 Private variable Python pair Private members provide limited support. Any shape is like __spam (at least two underscores, at the end of multiple single underscale), it is replaced with _classname__spam, removes the ClassName, which is the current-defined scribe, the current class name. This confusing does not care about the syntax position of the identifier, so it can be used to define private examples and class variables, methods, and global variables, and even save other classes as private variables. The confused name is more than 255 characters, it may take a truncation. The truncation does not occur when the class is outside the class, or the class name only contains an underscore. Named confusion is given to give a simple way to define "private" instance variables and methods in the class, avoiding the exemplary variable definition of derived classes to generate problems, or mix with variables in the outside code. It should be noted that the main purpose of confusion rules is to avoid accidental errors, which is already as private variables that may still be accessible or modified. It is also useful in specific occasions, such as debugging, this is also one of the reasons why this vulnerability has been blocked (small loopholes: derived class and base class to take the same name can use the private variables of the base class.) Note that the code incoming EXEC, EVAL () or evAlFile () will not call their categories as the current class, which is similar to the Global statement, and Global's role is limited to "the same batch" to perform byte compilation. Code. The same restrictions apply to getAttr (), setattr () and delattr (), and directly quote __dict__. 9.7 Supplement Sometimes the data type of "record" or C "structure" in Pascal is useful, which binds a set of named data items. A empty class definition can be good to implement this: Class Employee: Pass

John = Employee () # Create An Empty Employee Record

# Fill The Fields of the Record

John.name = 'john doe'

John.dept = 'computer lab'

John.salary = 1000 a certain Python code requires a special abstract data structure, usually in a class, in fact, this type of method. For example, if you have a function that is formatted from the file object, you can define a class with the read () and readline () methods to read the data from the string, then the class The object is incorporated into the aforementioned function as a parameter. Example method objects also have attributes: m.im_self is an object to which the instance method belongs, and M.IM_FUNC is a function object corresponding to this method. 9.8 Anomaly is also a class user-defined exception or a class. Use this mechanism to create an extendable exception system. The following is two new valid (semantic) exceptions: Raise Class, in the first form of instance, instance must be an example of Class or its derived class. The second form is the following form: Raise Instance .__ Class__, an exception that occurs in instance If it is the class listed in the abnormal subsis, or it is a class, then they are consistent (in turn - happening The exception has its type if it is the base class of the class listed in the abnormal subsequence, they do not match). For example, the following code prints B, C, D: Class B in order.

PASS

Class C (b):

PASS

Class D (c):

PASS

For C in [B, C, D]:

TRY:

Raise C ()

Except D:

Print "D"

Except C:

Print "C"

Except B:

Print "B" should be noted that if the order of the abnormal clause is reversed ("Execpt B" is in the forefront), it will print B, B, B - the first matching exception is triggered. When printing an exception class error message, print the class name first, then a space, a colon, then use the built-in function Str () to convert the class to the full string. 9.9 iterators Now you may notice that most container objects can be used in FOR Element In [1, 2, 3]:

Print Element

For Element In (1, 2, 3):

Print Element

For key in {'one': 1, 'two': 2}:

Print Key

For char in "123":

Print charr

For line in open ("myfile.txt"):

Print line This form of access is clear, simple, and convenient. This iterator is usually unparalleled in Python. In the background, the FOR statement calls iter () in the container object. This function returns an iterator object that defines the next () method, which is accessed one by one in the container one by one. When there is no subsequent element, Next () throws a stopiteration exception notification for the FOR statement cycle. The following is an example of its working principle: >>> s = 'ABC'

>>> IT = iter (s)

>>> IT

>>> it.next ()

'a'

>>> it.next ()

'b'

>>> it.next ()

'c' >>> it.next ()

TRACEBACK (MOST RECENT CALL LAST):

File "", line 1, in -toplevel

IT.next ()

The STOPITERATION understands the background mechanism of the iterator protocol, you can easily add an iterator behavior to your class. Define a __itor __ () method to return it to an object with a next () method. If this class has defined next (), then __iter __ () just returns to Self: >>> Class Reverse:

"Iterator for looping over a sequence backwards"

DEF __INIT __ (Self, DATA):

Self.Data = DATA

Self.index = LEN (DATA)

DEF __ITER __ (Self):

Return Self

Def next (Self):

if self.index == 0:

Raise StopIitration

Self.index = SELF.INDEX - 1

Return Self.Data [Self.index]

>>> for char in Reverse ('spam'):

Print charr

M

a

p

S 9.10 Generator generator is a simple and powerful tool for creating an iterator. They write like a regular function, use Yield statements when you need to return data. Each time next () is called, the generator replies the location it detachable (it memory the position of the statement and all the data values). The following example demonstrates that the generator can be created very simple: >>> Def Reverse (DATA):

For Index in Range (Len (DATA) -1, -1, -1):

Yield Data [index]

>>> for char in reverse ('golf'):

Print charr

fly

l

o

A class-based iterator is described in the previous section, and each of the events that can be made can also be made. Because the __iter __ () and next () methods are automatically created, the generator is so simple. Another key function is that local variables and execution between the two calls are automatically saved. This is easier than manually calling Self.index and Self.Data. In addition to the automatic method of creating and saving the program status, the StopItemization exception is automatically thrown when the generator is terminated. In summary, these functions make the easiest way to write a regular function to create an iterator.

FootNotes

... Namespaces

! 9.1

There is an exception. The module object has a secret read-only object called

__dict__, it returns a dictionary for implementing module namespace, named

__dict__ is an attribute instead of the global name. Obviously, use it violates the abstract principle implemented by namespace, it should be strictly limited to debugging.

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

New Post(0)