Python/Справочник по языку Python 3.1: различия между версиями

Содержимое удалено Содержимое добавлено
Добавлен перевод
Добавление перевода
Строка 259:
== 2.3. Идентификаторы и ключевые слова ==
 
Идентификаторы (также называемые "имена") описаныимеют следующимследующее лексическимлексическое определениемопределение.
 
Синтаксис идентификаторов в Питоне основывается на приложении «UAX-31» к стандарту «Unicode» , с переработкой и изменениями описанными ниже. Также смотрите дополнительные детали в «PEP 3131» .
 
В ASCII диапазоне (U+0001..U+007F) в идентификаторах допустимы только те же символы, что и в Питоне 2.x : буквы от «A» до «Z» в верхнем и нижнем регистре, подчеркивание «_» и, кроме первого символа идентификатора, – цифры от «0» до «9» .
 
В Питоне 3.0 введены дополнительные символы, не входящие в ASCII диапазон (см. PEP 3131). Для этих символов использована классификация из версии базы символов Unicode (Unicode Character Database), включенная в модуль «unicodedata» .
 
Идентификаторы не ограничены по длине и чувствительны к регистру.
 
identifier ::= id_start id_continue*
id_start ::= &lt все символы в общих категориях Lu, Ll, Lt, Lm, Lo, Nl, подчёркивание, и символы со свойством Other_ID_Start &gt
id_continue ::= &lt все символы в id_start, плюс символы в категориях Mn, Mc, Nd, Pc и другие символы со свойством Other_ID_Continue &gt
 
Использованные выше обозначения категорий Юникода :
 
* Lu - буквы в верхнем регистре
* Ll - буквы в нижнем регистре
* Lt - Заглавные буквы
* Lm - модифицирующие символы
* Lo - другие буквы
* Nl - буквенные числа
* Mn - непробельные знаки
* Mc - пробельные составные знаки
* Nd - десятичные цифры
* Pc - пунктуационные знаки
 
Все идентификаторы при лексическом разборе конвертируются в нормализованную форму NFC; и сравнение идентификаторов производится уже в форме NFC.
 
Ненормативный HTML файл со списком всех символов Юникода 4.1 , доступных для использования в идентификаторах, представлен здесь: http://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html .
 
 
 
 
== Продолжение перевода ==
 
<small>Перевод происходит, например, на : "http://notabenoid.com/book/5672/" ...</small>
 
<!--
 
 
 
 
2.3.1. Keywords¶
 
The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
 
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
 
2.3.2. Reserved classes of identifiers¶
 
Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters:
 
_*
 
Not imported by from module import *. The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. See section The import statement.
 
Note
 
The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.
__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library); applications should not expect to define additional names using this convention. The set of names of this class defined by Python may be extended in future versions. See section Special method names.
__*
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names).
 
2.4. Literals¶
 
Literals are notations for constant values of some built-in types.
2.4.1. String and Bytes literals¶
 
String literals are described by the following lexical definitions:
 
stringliteral ::= [stringprefix](shortstring | longstring)
stringprefix ::= "r" | "R"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | stringescapeseq
longstringitem ::= longstringchar | stringescapeseq
shortstringchar ::= <any source character except "\" or newline or the quote>
longstringchar ::= <any source character except "\">
stringescapeseq ::= "\" <any source character>
 
bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
longbyteschar ::= <any ASCII character except "\">
bytesescapeseq ::= "\" <any ASCII character>
 
One syntactic restriction not indicated by these productions is that whitespace is not allowed between the stringprefix or bytesprefix and the rest of the literal. The source character set is defined by the encoding declaration; it is UTF-8 if no encoding declaration is given in the source file; see section Encoding declarations.
 
In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
 
String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. As a result, '\U' and '\u' escapes in raw strings are not treated specially.
 
Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
 
In triple-quoted strings, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the string. (A “quote” is the character used to open the string, i.e. either ' or ".)
 
Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:
Escape Sequence Meaning Notes
\newline Backslash and newline ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo (1,3)
\xhh Character with hex value hh (2,3)
 
Escape sequences only recognized in string literals are:
Escape Sequence Meaning Notes
\N{name} Character named name in the Unicode database
\uxxxx Character with 16-bit hex value xxxx (4)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (5)
 
Notes:
 
1. As in Standard C, up to three octal digits are accepted.
2. Unlike in Standard C, at most two hex digits are accepted.
3. In a bytes literal, hexadecimal and octal escapes denote the byte with the given value. In a string literal, these escapes denote a Unicode character with the given value.
4. Individual code units which form parts of a surrogate pair can be encoded using this escape sequence. Unlike in Standard C, exactly two hex digits are required.
5. Any Unicode character can be encoded this way, but characters outside the Basic Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is compiled to use 16-bit code units (the default). Individual code units which form parts of a surrogate pair can be encoded using this escape sequence.
 
Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals.
 
Even in a raw string, string quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.
2.4.2. String literal concatenation¶
 
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:
 
re.compile("[A-Za-z_]" # letter or underscore
"[A-Za-z0-9_]*" # letter, digit or underscore
)
 
Note that this feature is defined at the syntactical level, but implemented at compile time. The ‘+’ operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings).
2.4.3. Numeric literals¶
 
There are three types of numeric literals: integers, floating point numbers, and imaginary numbers. There are no complex literals (complex numbers can be formed by adding a real number and an imaginary number).
 
Note that numeric literals do not include a sign; a phrase like -1 is actually an expression composed of the unary operator ‘-‘ and the literal 1.
2.4.4. Integer literals¶
 
Integer literals are described by the following lexical definitions:
 
integer ::= decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::= nonzerodigit digit* | "0"+
nonzerodigit ::= "1"..."9"
digit ::= "0"..."9"
octinteger ::= "0" ("o" | "O") octdigit+
hexinteger ::= "0" ("x" | "X") hexdigit+
bininteger ::= "0" ("b" | "B") bindigit+
octdigit ::= "0"..."7"
hexdigit ::= digit | "a"..."f" | "A"..."F"
bindigit ::= "0" | "1"
 
There is no limit for the length of integer literals apart from what can be stored in available memory.
 
Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.
 
Some examples of integer literals:
 
7 2147483647 0o177 0b100110111
3 79228162514264337593543950336 0o377 0x100000000
79228162514264337593543950336 0xdeadbeef
 
2.4.5. Floating point literals¶
 
Floating point literals are described by the following lexical definitions:
 
floatnumber ::= pointfloat | exponentfloat
pointfloat ::= [intpart] fraction | intpart "."
exponentfloat ::= (intpart | pointfloat) exponent
intpart ::= digit+
fraction ::= "." digit+
exponent ::= ("e" | "E") ["+" | "-"] digit+
 
Note that the integer and exponent parts are always interpreted using radix 10. For example, 077e010 is legal, and denotes the same number as 77e10. The allowed range of floating point literals is implementation-dependent. Some examples of floating point literals:
 
3.14 10. .001 1e100 3.14e-10 0e0
 
Note that numeric literals do not include a sign; a phrase like -1 is actually an expression composed of the unary operator - and the literal 1.
2.4.6. Imaginary literals¶
 
Imaginary literals are described by the following lexical definitions:
 
imagnumber ::= (floatnumber | intpart) ("j" | "J")
 
An imaginary literal yields a complex number with a real part of 0.0. Complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range. To create a complex number with a nonzero real part, add a floating point number to it, e.g., (3+4j). Some examples of imaginary literals:
 
3.14j 10.j 10j .001j 1e100j 3.14e-10j
 
2.5. Operators¶
 
The following tokens are operators:
 
+ - * ** / // %
<< >> & | ^ ~
< > <= >= == !=
 
2.6. Delimiters¶
 
The following tokens serve as delimiters in the grammar:
 
( ) [ ] { }
, : . ; @ =
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
 
The period can also occur in floating-point and imaginary literals. A sequence of three periods has a special meaning as an ellipsis literal. The second half of the list, the augmented assignment operators, serve lexically as delimiters, but also perform an operation.
 
The following printing ASCII characters have special meaning as part of other tokens or are otherwise significant to the lexical analyzer:
 
' " # \
 
The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error:
 
$ ?
 
 
-->
 
== Продолжение перевода ==