- 論壇徽章:
- 0
|
本章狀態(tài):自校完成
5. 表達(dá)式(Expressions)
¶
This chapter explains the meaning of the elements of expressions in Python.
本章描述了Python中表達(dá)式組成元素的含義。
Syntax Notes: In this and the following chapters, extended BNF notation will
be used to describe syntax, not lexical analysis. When (one alternative of) a
syntax rule has the form
語法注意: 在本章和之后的章節(jié)中,將使用擴(kuò)展BNF記法描述語法,而不是詞法分析。當(dāng)某語法規(guī)則(之一)具有如下形式,
name ::= othername
and no semantics are given, the semantics of this form of name are the same
as for othername.
并且沒有給出語義說明的時(shí)候,這種形式的 name 與 othername 具有相同的語義。
5.1. 數(shù)值型間的轉(zhuǎn)換(Arithmetic conversions)
¶
When a description of an arithmetic operator below uses the phrase “the numeric
arguments are converted to a common type,” this means that the operator
implementation for built-in types works that way:
在下面的數(shù)值運(yùn)算符描述中的“數(shù)值型參數(shù)被轉(zhuǎn)換為通用類型”,是指這些操作符對內(nèi)置類型按如下方式工作:
- If either argument is a complex number, the other is converted to complex;
如果其中一個(gè)參數(shù)是復(fù)數(shù),另一個(gè)也要轉(zhuǎn)換成復(fù)數(shù);
- otherwise, if either argument is a floating point number, the other is
converted to floating point;
否則,如果其中一個(gè)參數(shù)是浮點(diǎn)數(shù),另一個(gè)也要轉(zhuǎn)換成浮點(diǎn)數(shù);
- otherwise, both must be integers and no conversion is necessary.
否則, 兩個(gè)一定都是整數(shù), 不需要轉(zhuǎn)換。
Some additional rules apply for certain operators (e.g., a string left argument
to the ‘%’ operator). Extensions must define their own conversion behavior.
某些運(yùn)算符有特殊的規(guī)則(例如, ‘%’ 操作符左邊的字符串操作數(shù))。擴(kuò)展必須定義自己的轉(zhuǎn)換行為。
5.2. 原子(Atoms)
¶
Atoms are the most basic elements of expressions. The simplest atoms are
identifiers or literals. Forms enclosed in parentheses, brackets or braces are
also categorized syntactically as atoms. The syntax for atoms is:
原子是表達(dá)式最基本的組成單位。最簡單的原子是標(biāo)識符或者字面值。圓括號、方括號和大括號括住的文本在語法上也看成是原子,原子的語法如下:
atom ::=
identifier
|
literal
|
enclosure
enclosure ::=
parenth_form
|
list_display
|
dict_display
|
set_display
|
generator_expression
|
yield_atom
5.2.1. 標(biāo)識符(名字) (Identifiers (Names))
¶
An identifier occurring as an atom is a name. See section
標(biāo)識符和關(guān)鍵字(Identifiers and keywords)
for lexical definition and section
名字與綁定(Naming and binding)
for documentation of naming and
binding.
作為原子出現(xiàn)的標(biāo)識符是一個(gè)名字。關(guān)于詞法定義可參考
標(biāo)識符和關(guān)鍵字(Identifiers and keywords)
節(jié),名字與綁定的文檔可以參考
名字與綁定(Naming and binding)
節(jié)。
When the name is bound to an object, evaluation of the atom yields that object.
When a name is not bound, an attempt to evaluate it raises a
NameError
exception.
當(dāng)某名字綁定的是一個(gè)對象時(shí), 對該原子的求值(evaluation)就會導(dǎo)出(yield)那個(gè)對象. 當(dāng)沒有綁定名字而試圖對其求值(evaluate)時(shí),就會拋出
NameError
異常。
Private name mangling: When an identifier that textually occurs in a class
definition begins with two or more underscore characters and does not end in two
or more underscores, it is considered a private name of that class.
Private names are transformed to a longer form before code is generated for
them. The transformation inserts the class name in front of the name, with
leading underscores removed, and a single underscore inserted in front of the
class name. For example, the identifier __spam occurring in a class named
Ham will be transformed to _Ham__spam. This transformation is
independent of the syntactical context in which the identifier is used. If the
transformed name is extremely long (longer than 255 characters), implementation
defined truncation may happen. If the class name consists only of underscores,
no transformation is done.
私有名字變換: 在類定義中, 以兩個(gè)或更多下劃線開始, 但不以兩個(gè)或更多下劃線結(jié)束的標(biāo)識符,作為類的私有名字( private name )。在生成代碼之前,私有名字會被變換成更長的形式。這種變換是,在其前面插入類名(類名前的下劃線將被去掉),并在類名前插入一條下劃線。例如,在類 Ham 中定義的標(biāo)識符 __spam 會被變換成 _Ham__spam 。這種變換與使用標(biāo)識符的語法上下文無關(guān)。如果變換后的結(jié)果過長(超過255個(gè)字符),實(shí)現(xiàn)可能會截短名字。如果類名只由下劃線組成,就不進(jìn)行這種變換。
5.2.2. 字面值(Literals)
¶
Python supports string and bytes literals and various numeric literals:
Python支持字符串字面值、字節(jié)字面值和各種數(shù)值字面值:
literal ::=
stringliteral
|
bytesliteral
|
integer
|
floatnumber
|
imagnumber
Evaluation of a literal yields an object of the given type (string, bytes,
integer, floating point number, complex number) with the given value. The value
may be approximated in the case of floating point and imaginary (complex)
literals. See section
字面值(Literals)
for details.
對字面值求值會得到一個(gè)給定值的給定類型的對象(字符串、字節(jié)、整數(shù)、浮點(diǎn)數(shù)和復(fù)數(shù)),如果是浮點(diǎn)數(shù)和虛數(shù)(復(fù)數(shù)),那么這個(gè)值可能是個(gè)近似值,詳見
字面值(Literals)
一節(jié)的介紹。
With the exception of bytes literals, these all correspond to immutable data
types, and hence the object’s identity is less important than its value.
Multiple evaluations of literals with the same value (either the same occurrence
in the program text or a different occurrence) may obtain the same object or a
different object with the same value.
除了字節(jié)序列的字面值,所有字面值都屬于不可變的數(shù)據(jù)類型,因此對象的標(biāo)識比起它們的值來說顯得次要一些。多次使用相同的字面值(反復(fù)使用相同的程序代碼,或者在不同的地方出現(xiàn))獲得的可能是相同的對象或具有相同值的不同對象。
5.2.3. 括號表達(dá)式(Parenthesized forms)
¶
A parenthesized form is an optional expression list enclosed in parentheses:
括號表達(dá)式是位于一對圓括號之間的表達(dá)式列表(列表也可為空)。
parenth_form ::= "(" [
expression_list
] ")"
A parenthesized expression list yields whatever that expression list yields: if
the list contains at least one comma, it yields a tuple; otherwise, it yields
the single expression that makes up the expression list.
括號內(nèi)表達(dá)式列表的結(jié)果取決于其內(nèi)部表達(dá)式列表的結(jié)果:如果表達(dá)式列表中包括至少一個(gè)逗號, 它就生成一個(gè)元組;否則,就生成一個(gè)由表達(dá)式列表組成的表達(dá)式。
An empty pair of parentheses yields an empty tuple object. Since tuples are
immutable, the rules for literals apply (i.e., two occurrences of the empty
tuple may or may not yield the same object).
一對空圓括號會生成一個(gè)空的元組對象。因?yàn)樵M是不可變的,因此適用字面值的規(guī)則,即空元組的兩次出現(xiàn)可能(也可能不)生成相同對象。
Note that tuples are not formed by the parentheses, but rather by use of the
comma operator. The exception is the empty tuple, for which parentheses are
required — allowing unparenthesized “nothing” in expressions would cause
ambiguities and allow common typos to pass uncaught.
請注意元組并不是依靠圓括號構(gòu)成的,而是使用逗號。但空元組是個(gè)例外,此時(shí)圓括號是必須的 — 如果表達(dá)式中允許有不加圓括號的”空”可能會帶來歧義,出現(xiàn)一些易犯的錯(cuò)誤。
5.2.4. 列表、集合和字典的表示(Displays for lists, sets and dictionaries)
¶
For constructing a list, a set or a dictionary Python provides special syntax
called “displays”, each of them in two flavors:
為了構(gòu)造列表、集合和字典對象,Python提供了一種特殊語法,稱為“display”,分為兩類:
- either the container contents are listed explicitly, or
要么明確地列出容器對象的內(nèi)容。
- they are computed via a set of looping and filtering instructions, called a
comprehension.
要么通過一個(gè)循環(huán)和過濾方法的組合構(gòu)造,這稱為 comprehension 。
Common syntax elements for comprehensions are:
comprehension的通用語法是:
comprehension ::=
expression
comp_for
comp_for ::= "for"
target_list
"in"
or_test
[
comp_iter
]
comp_iter ::=
comp_for
|
comp_if
comp_if ::= "if"
expression_nocond
[
comp_iter
]
The comprehension consists of a single expression followed by at least one
for
clause and zero or more
for
or
if
clauses.
In this case, the elements of the new container are those that would be produced
by considering each of the
for
or
if
clauses a block,
nesting from left to right, and evaluating the expression to produce an element
each time the innermost block is reached.
comprehension由一個(gè)表達(dá)式,后跟至少一個(gè)
for
子句,然后是一個(gè)或多個(gè)
for
或
if
子句組成。此時(shí),這個(gè)新容器對象的元素是由每個(gè)從左到右嵌套的:keyword:for 和
if
子句產(chǎn)生的。每次執(zhí)行到最內(nèi)層代碼塊時(shí)計(jì)算前面那個(gè)表達(dá)式的值。
Note that the comprehension is executed in a separate scope, so names assigned
to in the target list don’t “l(fā)eak” in the enclosing scope.
注意,comprehension是在分開的作用域內(nèi)執(zhí)行的,因此,在目標(biāo)列表內(nèi)使用的臨時(shí)名字是不會“泄漏”出到上層作用域的。
5.2.5. 列表的display(List displays)
¶
A list display is a possibly empty series of expressions enclosed in square
brackets:
列表用一對方括號包圍的表達(dá)式序列(可能為空)表示:
list_display ::= "[" [
expression_list
|
comprehension
] "]"
A list display yields a new list object, the contents being specified by either
a list of expressions or a comprehension. When a comma-separated list of
expressions is supplied, its elements are evaluated from left to right and
placed into the list object in that order. When a comprehension is supplied,
the list is constructed from the elements resulting from the comprehension.
使用列表display會生成一個(gè)新的列表對象。它的內(nèi)容由一個(gè)表達(dá)式列表或comprehension給出。使用以逗號分隔的表達(dá)式列表
時(shí),Python會從左到右對每個(gè)元素求值然后按順序放進(jìn)列表對象中。如果是comprehension,列表由comprehension的計(jì)算結(jié)果組
成。
5.2.6. 集合的display(Set displays)
¶
A set display is denoted by curly braces and distinguishable from dictionary
displays by the lack of colons separating keys and values:
集合由一對大括號標(biāo)識,與字典的區(qū)別在于,集合不使用字典中鍵和值之間的冒號。
set_display ::= "{" (
expression_list
|
comprehension
) "}"
A set display yields a new mutable set object, the contents being specified by
either a sequence of expressions or a comprehension. When a comma-separated
list of expressions is supplied, its elements are evaluated from left to right
and added to the set object. When a comprehension is supplied, the set is
constructed from the elements resulting from the comprehension.
使用集合display會生成一個(gè)新的集合對象。它的內(nèi)容由一個(gè)表達(dá)式序列或comprehension給出。使用以逗號分隔的表達(dá)式列表
時(shí),Python會從左到右對每個(gè)元素求值然后按順序放進(jìn)集合對象中。如果是comprehension,集合由comprehension的計(jì)算結(jié)果組
成。
An empty set cannot be constructed with {}; this literal constructs an empty
dictionary.
空集合不能用 {} 建立;這個(gè)字面值表示的是空字典。
5.2.7. 字典display(Dictionary displays)
¶
A dictionary display is a possibly empty series of key/datum pairs enclosed in
curly braces:
字典用一對大括號括住的“鍵/值對”序列(可能為空)表示。
dict_display ::= "{" [
key_datum_list
|
dict_comprehension
] "}"
key_datum_list ::=
key_datum
(","
key_datum
)* [","]
key_datum ::=
expression
":"
expression
dict_comprehension ::=
expression
":"
expression
comp_for
A dictionary display yields a new dictionary object.
使用字典display會生成一個(gè)新的字典對象。
If a comma-separated sequence of key/datum pairs is given, they are evaluated
from left to right to define the entries of the dictionary: each key object is
used as a key into the dictionary to store the corresponding datum. This means
that you can specify the same key multiple times in the key/datum list, and the
final dictionary’s value for that key will be the last one given.
使用以逗號分隔的“鍵/值對”列表時(shí),Python會從左到右地定義字典中的每個(gè)元素;每個(gè)鍵對象作為字典一個(gè)鍵值存儲對應(yīng)的數(shù)據(jù)。這意味著你可以在這個(gè)“鍵/值對”列表中多次使用相同鍵,但只有最后一次使用的值會保存下來。
A dict comprehension, in contrast to list and set comprehensions, needs two
expressions separated with a colon followed by the usual “for” and “if” clauses.
When the comprehension is run, the resulting key and value elements are inserted
in the new dictionary in the order they are produced.
字典comprehension與列表和集合的不同在于,它需要用冒號分隔的兩個(gè)表達(dá)式,之后再尾隨著通常的”for”和”if”子句。當(dāng)comprehension運(yùn)行時(shí),結(jié)果“鍵值對”按產(chǎn)生順序加入到新字典中。
Restrictions on the types of the key values are listed earlier in section
標(biāo)準(zhǔn)類型層次(The standard type hierarchy)
. (To summarize, the key type should be
hashable
, which excludes
all mutable objects.) Clashes between duplicate keys are not detected; the last
datum (textually rightmost in the display) stored for a given key value
prevails.
關(guān)于鍵值的類型限制已經(jīng)在之前的
標(biāo)準(zhǔn)類型層次(The standard type hierarchy)
一節(jié)中有所介紹(概要地講,鍵的類型應(yīng)該是
hashable
的,這排除了所有可變對象)。無論是哪種方法,都不會檢查相同鍵導(dǎo)致的沖突,只有最后一個(gè)數(shù)據(jù)項(xiàng)(在書寫上是最右邊的)才會保留到字典中。
5.2.8. Generator表達(dá)式(Generator expressions)
¶
A generator expression is a compact generator notation in parentheses:
Generator表達(dá)式是圓括號內(nèi)的一個(gè)緊湊的generator記法。
generator_expression ::= "("
expression
comp_for
")"
A generator expression yields a new generator object. Its syntax is the same as
for comprehensions, except that it is enclosed in parentheses instead of
brackets or curly braces.
Generator表達(dá)式會構(gòu)造一個(gè)generator對象。它的語法與comprehension相同,除了兩端是圓括號,而不是方括號或者大括號。
Variables used in the generator expression are evaluated lazily when the
__next__() method is called for generator object (in the same fashion as
normal generators). However, the leftmost
for
clause is immediately
evaluated, so that an error produced by it can be seen before any other possible
error in the code that handles the generator expression. Subsequent
for
clauses cannot be evaluated immediately since they may depend on
the previous
for
loop. For example: (x*y for x in range(10) for y
in bar(x)).
Generator表達(dá)式中的變量會被推遲到調(diào)用generator對象的 __next__() 方法時(shí)計(jì)算,這與普通generator對象相同。但是,最左的
for
子句會立即得到調(diào)用,所以這個(gè)子句中的錯(cuò)誤會在任何處理generator表達(dá)式的代碼中的錯(cuò)誤之前發(fā)現(xiàn)。其后的
for
子句不會被立即計(jì)算,因?yàn)樗麄兛赡芤蕾囉谇懊娴?
for
循環(huán),例如: (x*y for x in range(10) for y in bar(x)) 。
The parentheses can be omitted on calls with only one argument. See section
調(diào)用(Calls)
for the detail.
如果調(diào)用只有一個(gè)參數(shù),那么可以省略這個(gè)括號,見
調(diào)用(Calls)
。
5.2.9. Yield表達(dá)式(Yield expressions)
¶
yield_atom ::= "("
yield_expression
")"
yield_expression ::= "yield" [
expression_list
]
The
yield
expression is only used when defining a generator function,
and can only be used in the body of a function definition. Using a
yield
expression in a function definition is sufficient to cause that
definition to create a generator function instead of a normal function.
yield
表達(dá)式只能在定義generator函數(shù)時(shí)使用,并且只能用于函數(shù)體內(nèi)。在函數(shù)定義中使用
yield
表達(dá)式會使這個(gè)函數(shù)成為generator函數(shù),而不是正常函數(shù)。
When a generator function is called, it returns an iterator known as a
generator. That generator then controls the execution of a generator function.
The execution starts when one of the generator’s methods is called. At that
time, the execution proceeds to the first
yield
expression, where it
is suspended again, returning the value of
expression_list
to
generator’s caller. By suspended we mean that all local state is retained,
including the current bindings of local variables, the instruction pointer, and
the internal evaluation stack. When the execution is resumed by calling one of
the generator’s methods, the function can proceed exactly as if the
yield
expression was just another external call. The value of the
yield
expression after resuming depends on the method which resumed
the execution.
在調(diào)用一個(gè)generator函數(shù)時(shí),它會返回一個(gè)generator對象作為迭代器。這個(gè)generator對象控制著generator函數(shù)的執(zhí)行。調(diào)用這個(gè)generator對象的方法調(diào)用時(shí),函數(shù)就會開始執(zhí)行,這時(shí),函數(shù)會處理第一個(gè)
yield
表達(dá)式,并在這里暫停執(zhí)行函數(shù),還會返回表達(dá)式
expression_list
的值給generator對象的調(diào)用者。函數(shù)暫停執(zhí)行意味著所有的局部狀態(tài)都被保存下來了,包括局部變量的當(dāng)前綁定、指令指針和內(nèi)部棧。在調(diào)用某個(gè)generator對象的方法時(shí),函數(shù)就會恢復(fù)執(zhí)行,就好像
yield
表達(dá)式只是一個(gè)對外部功能的調(diào)用一樣。在恢復(fù)執(zhí)行時(shí),
yield
表達(dá)式的值依賴于恢復(fù)執(zhí)行時(shí)調(diào)用的什么方法。
All of this makes generator functions quite similar to coroutines; they yield
multiple times, they have more than one entry point and their execution can be
suspended. The only difference is that a generator function cannot control
where should the execution continue after it yields; the control is always
transfered to the generator’s caller.
這種generator函數(shù)的所有特征與coroutines很相近:他們都多次產(chǎn)生(yield)值,他們有多個(gè)入口點(diǎn)并且執(zhí)行可以暫停。唯一的
差異在于generator函數(shù)在產(chǎn)生(yield)值之后無法控制在什么地方繼續(xù)執(zhí)行,控制權(quán)會轉(zhuǎn)移到generator的調(diào)用者上面。
The
yield
statement is allowed in the
try
clause of a
try
...
finally
construct. If the generator is not
resumed before it is finalized (by reaching a zero reference count or by being
garbage collected), the generator-iterator’s close() method will be
called, allowing any pending
finally
clauses to execute.
yield
語句可以出現(xiàn)在
try
...
finally
構(gòu)造中的
try
子句中。如果一個(gè)generator對象在終結(jié)(引用計(jì)數(shù)變?yōu)?,或者被垃圾回收)之前沒有能恢復(fù)執(zhí)行,就會調(diào)用的generator對象 close() 方法,給等待的
finally
子句執(zhí)行的機(jī)會。
The following generator’s methods can be used to control the execution of a
generator function:
以下generator的方法用于控制generator函數(shù)的執(zhí)行:
generator.__next__()
¶
Starts the execution of a generator function or resumes it at the last
executed
yield
expression. When a generator function is resumed
with a __next__() method, the current
yield
expression
always evaluates to
None
. The execution then continues to the next
yield
expression, where the generator is suspended again, and the
value of the
expression_list
is returned to
next()
‘s caller.
If the generator exits without yielding another value, a
StopIteration
exception is raised.
開始generator函數(shù)的執(zhí)行,或者從上次執(zhí)行的
yield
表達(dá)式處恢復(fù)執(zhí)行。當(dāng)使用 __next__() 方法恢復(fù)generator函數(shù)的執(zhí)行時(shí),當(dāng)前
yield
表達(dá)式都會被計(jì)算成
None
。執(zhí)行然后會繼續(xù)到下次遇見
yield
表達(dá)式,generator函數(shù)會再次被掛起,表達(dá)式
expression_list
的值會被返回給
next()
的調(diào)用者。如果generator函數(shù)沒有產(chǎn)生(yield)新值就直接退出了,就會導(dǎo)致拋出異常
StopIteration
。
This method is normally called implicitly, e.g. by a
for
loop, or
by the built-in
next()
function.
通常不會直接調(diào)用這個(gè)方法,而是通過像
for
循環(huán)或內(nèi)置的
next()
函數(shù)隱式地使用它。
generator.send(value)
¶
Resumes the execution and “sends” a value into the generator function. The
value argument becomes the result of the current
yield
expression. The send() method returns the next value yielded by the
generator, or raises
StopIteration
if the generator exits without
yielding another value. When send() is called to start the generator,
it must be called with
None
as the argument, because there is no
yield
expression that could receive the value.
恢復(fù)執(zhí)行,并給generator函數(shù)“發(fā)送”一個(gè)值。 value 參數(shù)的值會成為當(dāng)前
yield
表達(dá)式的結(jié)果, send() 方法會返回generator函數(shù)產(chǎn)生的下一個(gè)值,或者它沒有產(chǎn)生(yield)其它值便退出時(shí)就拋出異常
StopIteration
。使用 send() 方法啟動一個(gè)generator函數(shù)時(shí),必須使用
None
作為參數(shù),因?yàn)檫@時(shí)沒有任何
yield
表達(dá)式可以接收這個(gè)值。
generator.throw(type[, value[, traceback]])
¶
Raises an exception of type type at the point where generator was paused,
and returns the next value yielded by the generator function. If the generator
exits without yielding another value, a
StopIteration
exception is
raised. If the generator function does not catch the passed-in exception, or
raises a different exception, then that exception propagates to the caller.
在generator函數(shù)暫停點(diǎn)上拋出一個(gè)類型為 type 的異常,并返回generator函數(shù)產(chǎn)生(yield)的下一個(gè)值。generator函數(shù)沒有產(chǎn)生(yield)其它值便退出時(shí)就拋出異常
StopIteration
。如果generator沒有捕獲這個(gè)傳入的異常,或者拋出了一個(gè)不同的異常,那么這個(gè)異常會傳播給調(diào)用者處理。
generator.close()
¶
Raises a
GeneratorExit
at the point where the generator function was
paused. If the generator function then raises
StopIteration
(by
exiting normally, or due to already being closed) or
GeneratorExit
(by
not catching the exception), close returns to its caller. If the generator
yields a value, a
RuntimeError
is raised. If the generator raises any
other exception, it is propagated to the caller. close() does nothing
if the generator has already exited due to an exception or normal exit.
在generator函數(shù)被暫停點(diǎn)拋出異常
GeneratorExit
。如果generator函數(shù)之后拋出了異常
StopIteration
(通過正常退出,或者是已經(jīng)關(guān)閉了),或者
GeneratorExit
(因?yàn)闆]有捕獲這個(gè)異常),那么close會返回到調(diào)用者。如果generator函數(shù)產(chǎn)生(yield)了一個(gè)值,那么就會拋出
RuntimeError
異常。如果generator函數(shù)拋出了任何其他異常,它都會傳播給其調(diào)用者。如果generator函數(shù)因?yàn)楫惓;蛘呤钦M顺鲆呀?jīng)關(guān)閉了, close() 方法什么也不會做。
Here is a simple example that demonstrates the behavior of generators and
generator functions:
下面是一個(gè)簡單的例子演示了generator和generator函數(shù)的行為:
>>> def echo(value=None):
... print("Execution starts when 'next()' is called for the first time.")
... try:
... while True:
... try:
... value = (yield value)
... except Exception as e:
... value = e
... finally:
... print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.
See also
PEP 0255
- Simple GeneratorsThe proposal for adding generators and the
yield
statement to Python.
為Python增加generator和
yield
語句的提案。
PEP 0342
- Coroutines via Enhanced GeneratorsThe proposal to enhance the API and syntax of generators, making them
usable as simple coroutines.
改進(jìn)generator API和語法,使其像簡單coroutine一樣可用的提案。
5.3. 基元(Primaries)
¶
Primaries represent the most tightly bound operations of the language. Their
syntax is:
基元是指和語言本身中關(guān)系最緊密的操作。它們的語法如下:
primary ::=
atom
|
attributeref
|
subscription
|
slicing
|
call
5.3.1. 屬性引用(Attribute references)
¶
An attribute reference is a primary followed by a period and a name:
屬性引用由一個(gè)基元(primary)后跟一個(gè)句號和一個(gè)名字構(gòu)成:
attributeref ::=
primary
"."
identifier
The primary must evaluate to an object of a type that supports attribute
references, which most objects do. This object is then asked to produce the
attribute whose name is the identifier (which can be customized by overriding
the
__getattr__()
method). If this attribute is not available, the
exception
AttributeError
is raised. Otherwise, the type and value of the
object produced is determined by the object. Multiple evaluations of the same
attribute reference may yield different objects.
基元必須是一個(gè)計(jì)算(evalute)出來的支持屬性引用的類型的實(shí)例,多數(shù)情況下指一個(gè)對象。然后,會要求這個(gè)對象生成屬性,其 identifer 的名字就是屬性名(這一步可以通過
__getattr__()
方法覆蓋定制)。如果該屬性無效,就會拋出異常
AttributeError
。否則,對象本身就確定了屬性的類型和值。對同一屬性的多次求值(evaluation)可能會創(chuàng)建不同的對象。
5.3.2. 下標(biāo)(Subscriptions)
¶
A subscription selects an item of a sequence (string, tuple or list) or mapping
(dictionary) object:
下標(biāo)會選擇一個(gè)有序類型對象(字符串、元組和列表)或映射(字典)對象中的一項(xiàng):
subscription ::=
primary
"["
expression_list
"]"
The primary must evaluate to an object that supports subscription, e.g. a list
or dictionary. User-defined objects can support subscription by defining a
__getitem__()
method.
基元(primary)必須是一個(gè)計(jì)算出來的支持下標(biāo)的對象,例如列表或者字典。用戶定義對象可以通過定義
__getitem__()
支持下標(biāo)。
For built-in objects, there are two types of objects that support subscription:
有兩種內(nèi)置對象可以支持下標(biāo):
If the primary is a mapping, the expression list must evaluate to an object
whose value is one of the keys of the mapping, and the subscription selects the
value in the mapping that corresponds to that key. (The expression list is a
tuple except if it has exactly one item.)
如果基元是一個(gè)映射,對 expression_list 求值的結(jié)果必須是映射的一個(gè)鍵。然后此下標(biāo)在基元映射中選擇與該鍵所對應(yīng)的值。(除非 expression_list 只有一項(xiàng),否則它就是一個(gè)元組)
If the primary is a sequence, the expression (list) must evaluate to an integer.
If this value is negative, the length of the sequence is added to it (so that,
e.g., x[-1] selects the last item of x.) The resulting value must be a
nonnegative integer less than the number of items in the sequence, and the
subscription selects the item whose index is that value (counting from zero).
如果基元是一個(gè)有序類型,則 expression_list 的計(jì)算結(jié)果應(yīng)該是一個(gè)整數(shù)。如果這個(gè)值是負(fù)的,就加上該基元的長度(所以,例如 x[-1] 就會選擇 x 的最后一項(xiàng))。計(jì)算結(jié)果必須是小于基元中元素?cái)?shù)的非負(fù)整數(shù),并且此下標(biāo)操作選擇以該數(shù)為索引(從0開始計(jì))的值。
A string’s items are characters. A character is not a separate data type but a
string of exactly one character.
字符串的元素是字符。字符不是單獨(dú)的數(shù)據(jù)類型,而是只包括一個(gè)字符的字符串。
5.3.3. 片斷(Slicings)
¶
A slicing selects a range of items in a sequence object (e.g., a string, tuple
or list). Slicings may be used as expressions or as targets in assignment or
del
statements. The syntax for a slicing:
片斷選擇某個(gè)有序類型對象(如字符串、元組或者列表)的若干個(gè)元素。片斷可以作為表達(dá)式使用,也可以作為賦值和 del 語句的目標(biāo)。下面是片斷的語法:
slicing ::=
primary
"["
slice_list
"]"
slice_list ::=
slice_item
(","
slice_item
)* [","]
slice_item ::=
expression
|
proper_slice
proper_slice ::= [
lower_bound
] ":" [
upper_bound
] [ ":" [
stride
] ]
lower_bound ::=
expression
upper_bound ::=
expression
stride ::=
expression
There is ambiguity in the formal syntax here: anything that looks like an
expression list also looks like a slice list, so any subscription can be
interpreted as a slicing. Rather than further complicating the syntax, this is
disambiguated by defining that in this case the interpretation as a subscription
takes priority over the interpretation as a slicing (this is the case if the
slice list contains no proper slice).
在這里形式語法的說明中有點(diǎn)含糊:任何看起來像表達(dá)式列表的結(jié)構(gòu)也可以看作是片斷列表,所以任何下標(biāo)都可以解釋為片斷。為了避免語法的復(fù)雜化,我們這樣避免歧義:這樣的結(jié)構(gòu)我們優(yōu)先判斷為下標(biāo),其次作為表達(dá)式列表(即不包括片斷列表沒有包括適當(dāng)片斷的時(shí)候)。
The semantics for a slicing are as follows. The primary must evaluate to a
mapping object, and it is indexed (using the same
__getitem__()
method as
normal subscription) with a key that is constructed from the slice list, as
follows. If the slice list contains at least one comma, the key is a tuple
containing the conversion of the slice items; otherwise, the conversion of the
lone slice item is the key. The conversion of a slice item that is an
expression is that expression. The conversion of a proper slice is a slice
object (see section
標(biāo)準(zhǔn)類型層次(The standard type hierarchy)
) whose start, stop and
step attributes are the values of the expressions given as lower bound,
upper bound and stride, respectively, substituting None for missing
expressions.
片斷的語義如下:primary必須被計(jì)算成一個(gè)映射對象,并且它以從slice list中構(gòu)造出的鍵作為索引(與下標(biāo)的工作方式相同,即通過方法
__getitem__()
)。如果slice list包括至少一個(gè)逗號,鍵就是一個(gè)從片斷項(xiàng)轉(zhuǎn)換的元組,否則,唯一的片斷項(xiàng)就作為鍵。本身就是表達(dá)式的片斷項(xiàng)的轉(zhuǎn)換結(jié)果就是該表達(dá)式。一個(gè)適當(dāng)片斷在轉(zhuǎn)換后就是片斷對象(參見
標(biāo)準(zhǔn)類型層次(The standard type hierarchy)
一節(jié)),屬性 start 、 stop 和 step 分別是作為下界、上界、步長的表達(dá)式的值,如果缺少對應(yīng)的表達(dá)式,就用 None 補(bǔ)齊。
5.3.4. 調(diào)用(Calls)
¶
A call calls a callable object (e.g., a function) with a possibly empty series
of arguments:
調(diào)用就是以一系列參數(shù)(可能為空)調(diào)用一個(gè)可調(diào)用對象(例如函數(shù)):
call ::=
primary
"(" [
argument_list
[","] |
comprehension
] ")"
argument_list ::=
positional_arguments
[","
keyword_arguments
]
["," "*"
expression
] [","
keyword_arguments
]
["," "**"
expression
]
|
keyword_arguments
["," "*"
expression
]
[","
keyword_arguments
] ["," "**"
expression
]
| "*"
expression
[","
keyword_arguments
] ["," "**"
expression
]
| "**"
expression
positional_arguments ::=
expression
(","
expression
)*
keyword_arguments ::=
keyword_item
(","
keyword_item
)*
keyword_item ::=
identifier
"="
expression
A trailing comma may be present after the positional and keyword arguments but
does not affect the semantics.
在位置參數(shù)和關(guān)鍵字參數(shù)之后可以尾隨一個(gè)逗號,但它對語義沒有任何影響。
The primary must evaluate to a callable object (user-defined functions, built-in
functions, methods of built-in objects, class objects, methods of class
instances, and all objects having a
__call__()
method are callable). All
argument expressions are evaluated before the call is attempted. Please refer
to section
函數(shù)定義(Function definitions)
for the syntax of formal parameter lists.
基元,必須被計(jì)算成一個(gè)可調(diào)用對象(用戶定義函數(shù)、內(nèi)置函數(shù)、內(nèi)置方法對象、類對象、類實(shí)例方法、和所有其他定義了
__call__()
方法模擬可調(diào)用對象的對象。)所有參數(shù)表達(dá)都在調(diào)用執(zhí)行之前計(jì)算,關(guān)于形參表的語法參見
函數(shù)定義(Function definitions)
一節(jié)。
If keyword arguments are present, they are first converted to positional
arguments, as follows. First, a list of unfilled slots is created for the
formal parameters. If there are N positional arguments, they are placed in the
first N slots. Next, for each keyword argument, the identifier is used to
determine the corresponding slot (if the identifier is the same as the first
formal parameter name, the first slot is used, and so on). If the slot is
already filled, a
TypeError
exception is raised. Otherwise, the value of
the argument is placed in the slot, filling it (even if the expression is
None, it fills the slot). When all arguments have been processed, the slots
that are still unfilled are filled with the corresponding default value from the
function definition. (Default values are calculated, once, when the function is
defined; thus, a mutable object such as a list or dictionary used as default
value will be shared by all calls that don’t specify an argument value for the
corresponding slot; this should usually be avoided.) If there are any unfilled
slots for which no default value is specified, a
TypeError
exception is
raised. Otherwise, the list of filled slots is used as the argument list for
the call.
如果有關(guān)鍵字參數(shù),它們會先按如下步驟轉(zhuǎn)換為位置參數(shù):第一步、根據(jù)形參表創(chuàng)建一串空閑槽,如果有N個(gè)位置參數(shù),
它們就被放在前N個(gè)槽中。然后,對于每個(gè)關(guān)鍵字參數(shù),根據(jù)它的標(biāo)識符名字確定其對應(yīng)的槽(如果其標(biāo)識符與第一個(gè)形參數(shù)名相同,它就占用第一個(gè)槽,以此類
推)。如果發(fā)現(xiàn)某個(gè)槽已經(jīng)被占用,就是導(dǎo)致
TypeError
異常,否則將參數(shù)的值(即使為
None
)放進(jìn)槽中。當(dāng)處理完所有關(guān)鍵字參數(shù)后,所有未填充的槽用函數(shù)定義中的默認(rèn)值填充(默認(rèn)值是在函數(shù)定義時(shí)計(jì)算出來的,所以當(dāng)使用列表和字典這種可變類型對
象做默認(rèn)值時(shí),它們就會被那些沒有為相應(yīng)槽指定參數(shù)的調(diào)用所共享,一般情況要避免這些)。如果仍有未填充無默認(rèn)值的槽位,就會拋出
TypeError
異常。否則,所有被填充的槽就當(dāng)作調(diào)用的參數(shù)表使用了。
Note
An implementation may provide built-in functions whose positional parameters do
not have names, even if they are ‘named’ for the purpose of documentation, and
which therefore cannot be supplied by keyword. In CPython, this is the case for
functions implemented in C that use
PyArg_ParseTuple()
to parse their
arguments.
實(shí)現(xiàn)提供的內(nèi)置函數(shù)的位置參數(shù)可能根本就沒有名字,即使它們在文檔中是有名字的。因此不能用關(guān)鍵字方法指定。在CPython里,當(dāng)使用C語言的
PyArg_ParseTuple()
解析函數(shù)參數(shù)時(shí)就是這種情況。
If there are more positional arguments than there are formal parameter slots, a
TypeError
exception is raised, unless a formal parameter using the syntax
*identifier is present; in this case, that formal parameter receives a tuple
containing the excess positional arguments (or an empty tuple if there were no
excess positional arguments).
在形式參數(shù)沒有使用 *identifier 語法,并且位置參數(shù)多于形參槽數(shù)就會導(dǎo)致
TypeError
異常。在使用該種語法時(shí),形參會接受一個(gè)包括有額外位置參數(shù)的元組(如果沒有額外的位置參數(shù),元組就為空)。
If any keyword argument does not correspond to a formal parameter name, a
TypeError
exception is raised, unless a formal parameter using the syntax
**identifier is present; in this case, that formal parameter receives a
dictionary containing the excess keyword arguments (using the keywords as keys
and the argument values as corresponding values), or a (new) empty dictionary if
there were no excess keyword arguments.
如果有任何一個(gè)關(guān)鍵字參數(shù)沒有對應(yīng)形參名字,并且形參列表里沒有使用 **identifier 語法,就會引發(fā)
TypeError
異常。使用該種語法時(shí)。形參會接受一個(gè)包括有額外關(guān)鍵字參數(shù)的字典(關(guān)鍵字是鍵,參數(shù)值作為對應(yīng)的值);如果沒有額外的關(guān)鍵字參數(shù),這個(gè)(新)字典就為空。
If the syntax *expression appears in the function call, expression must
evaluate to a sequence. Elements from this sequence are treated as if they were
additional positional arguments; if there are positional arguments x1,...,
xN, and expression evaluates to a sequence y1, ..., yM, this is
equivalent to a call with M+N positional arguments x1, ..., xN, y1, ...,
yM.
如果在函數(shù)調(diào)用中使用了 *expression ,那么 expression 的計(jì)算結(jié)果必須是有序類型,這個(gè)有序類型對象的元素按額外的位置參數(shù)處理。如果存在有位置參數(shù) x1 ,..., xN ,并且 *exprsseion 的計(jì)算結(jié)果為 y1 ,..., yM ,那么函數(shù)就是有M+N個(gè)參數(shù)了, x1 , ..., xN , y1 , ...,yM 。
A consequence of this is that although the *expression syntax may appear
after some keyword arguments, it is processed before the keyword arguments
(and the **expression argument, if any – see below). So:
由此可以得到一個(gè)推論,盡管 *expression 可以出現(xiàn)在關(guān)鍵字參數(shù) 之后 ,但它會在處理關(guān)鍵字參數(shù) 之前 得到處理。(如果有的話, **expression 也是如此,見下述),所以:
>>> def f(a, b):
... print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
File "", line 1, in ?
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
It is unusual for both keyword arguments and the *expression syntax to be
used in the same call, so in practice this confusion does not arise.
同時(shí)使用關(guān)鍵字參數(shù)和 *expression 調(diào)用的情況并不常見,所以在實(shí)踐中這種混亂很少發(fā)生。
If the syntax **expression appears in the function call, expression must
evaluate to a mapping, the contents of which are treated as additional keyword
arguments. In the case of a keyword appearing in both expression and as an
explicit keyword argument, a
TypeError
exception is raised.
如果在函數(shù)調(diào)用中使用 **expression ,那么 expression 的計(jì)算結(jié)果必須是一個(gè)映射類型的對象,其內(nèi)容作為附加的關(guān)鍵字參數(shù)。如果一個(gè)關(guān)鍵字同時(shí)出現(xiàn)在 expression 中和顯式關(guān)鍵字參數(shù)中,就會拋出
TypeError
異常。
Formal parameters using the syntax *identifier or **identifier cannot be
used as positional argument slots or as keyword argument names.
使用 *identifier 或 **identifier 語法形式的形參不能作為位置參數(shù)槽,或者作為關(guān)鍵字參數(shù)名。
A call always returns some value, possibly None, unless it raises an
exception. How this value is computed depends on the type of the callable
object.
如果調(diào)用沒有拋出異常,通常會返回一些值,有可能為 None 。這個(gè)值如何計(jì)算依賴于可調(diào)用對象的類型。
If it is—
如果它是 ——
a user-defined function:The code block for the function is executed, passing it the argument list. The
first thing the code block will do is bind the formal parameters to the
arguments; this is described in section
函數(shù)定義(Function definitions)
. When the code block
executes a
return
statement, this specifies the return value of the
function call.
用戶定義函數(shù)。執(zhí)行此函數(shù)的代碼塊,并把參數(shù)傳給它。這個(gè)代碼塊要做的第一件事就是將形參與實(shí)參對應(yīng)起來,關(guān)于這點(diǎn)參見
函數(shù)定義(Function definitions)
。當(dāng)代碼塊執(zhí)行到
return
語句時(shí),會指定這次函數(shù)調(diào)用的返回值。
a built-in function or method:The result is up to the interpreter; see
Built-in Functions
for the
descriptions of built-in functions and methods.
內(nèi)置函數(shù)或者方法。結(jié)果依賴于解釋器,參見
Built-in Functions
的相應(yīng)介紹。
a class object:A new instance of that class is returned.
類對象。返回這個(gè)類的一個(gè)新實(shí)例。
a class instance method:The corresponding user-defined function is called, with an argument list that is
one longer than the argument list of the call: the instance becomes the first
argument.
調(diào)用對應(yīng)的用戶定義函數(shù),比普通的函數(shù)調(diào)用多一個(gè)參數(shù):該實(shí)例成為方法的第一個(gè)參數(shù)。
a class instance:The class must define a
__call__()
method; the effect is then the same as
if that method was called.
類實(shí)例。類實(shí)例必須定義方法
__call__()
,效果同對該方法的調(diào)用。
5.4. 冪運(yùn)算符(The power operator)
¶
The power operator binds more tightly than unary operators on its left; it binds
less tightly than unary operators on its right. The syntax is:
冪運(yùn)算符比它左邊的一元運(yùn)算符的優(yōu)先級更高; 但比右邊的一元運(yùn)算符要低。語法為:
power ::=
primary
["**"
u_expr
]
Thus, in an unparenthesized sequence of power and unary operators, the operators
are evaluated from right to left (this does not constrain the evaluation order
for the operands): -1**2 results in -1.
因此, 在一個(gè)沒有額外括號的冪運(yùn)算符和一元運(yùn)算符序列中,求值會從右至左進(jìn)行(這點(diǎn)對操作數(shù)本身的求值順序沒有影響): -1**2 會計(jì)算為 -1 。
The power operator has the same semantics as the built-in
pow()
function,
when called with two arguments: it yields its left argument raised to the power
of its right argument. The numeric arguments are first converted to a common
type, and the result is of that type.
當(dāng)以兩個(gè)參數(shù)調(diào)用內(nèi)置函數(shù)
pow()
時(shí),冪運(yùn)算符與它有相同的語義:生成左邊參數(shù)值的右邊參數(shù)值次方的計(jì)算結(jié)果。數(shù)值型參數(shù)先被轉(zhuǎn)換成通用類型,結(jié)果的類型與參數(shù)類型相同。
For int operands, the result has the same type as the operands unless the second
argument is negative; in that case, all arguments are converted to float and a
float result is delivered. For example, 10**2 returns 100, but
10**-2 returns 0.01.
對于整數(shù)操作數(shù),如果第二個(gè)參數(shù)不是負(fù)數(shù),結(jié)果類型與操作數(shù)相同。否則,所以參數(shù)先被轉(zhuǎn)換為浮點(diǎn)數(shù),并產(chǎn)生一個(gè)浮點(diǎn)結(jié)果。例如, 10**2 返回 100 ,但10**-2 返回 0.01 。
Raising 0.0 to a negative power results in a
ZeroDivisionError
.
Raising a negative number to a fractional power results in a
complex
number. (In earlier versions it raised a
ValueError
.)
計(jì)算 0.0 的負(fù)數(shù)次冪時(shí)會拋出
ZeroDivisionError
異常。計(jì)算負(fù)數(shù)的分?jǐn)?shù)次冪會生成一個(gè)
complex
值(之前版本會拋出
ValueError
異常)。
5.5. 一元算術(shù)運(yùn)算和位運(yùn)算(Unary arithmetic and bitwise operations)
¶
All unary arithmetic and bitwise operations have the same priority:
所有一元算術(shù)運(yùn)算符和位運(yùn)算符有相同的優(yōu)先級:
u_expr ::=
power
| "-"
u_expr
| "+"
u_expr
| "~"
u_expr
The unary - (minus) operator yields the negation of its numeric argument.
一元運(yùn)算符 - (減)取數(shù)值型操作數(shù)的負(fù)值。
The unary + (plus) operator yields its numeric argument unchanged.
一元運(yùn)算符 + (加)取數(shù)值型操作數(shù)值本身。
The unary ~ (invert) operator yields the bitwise inversion of its integer
argument. The bitwise inversion of x is defined as -(x+1). It only
applies to integral numbers.
一元運(yùn)算符 ~ (取反)會對其整數(shù)參數(shù)求逆(比特級)。 x 的比特級求逆運(yùn)算定義為 -(x+1) 。這個(gè)運(yùn)算符只用于整數(shù)操作數(shù)。
In all three cases, if the argument does not have the proper type, a
TypeError
exception is raised.
在所有以上三種情況下,如果參數(shù)的類型不合法,就會引發(fā)一個(gè)
TypeError
異常。
5.6. 二元算術(shù)運(yùn)算(Binary arithmetic operations)
¶
The binary arithmetic operations have the conventional priority levels. Note
that some of these operations also apply to certain non-numeric types. Apart
from the power operator, there are only two levels, one for multiplicative
operators and one for additive operators:
二元算術(shù)運(yùn)算符的優(yōu)先級符合我們的正常習(xí)慣。但要注意其中有些運(yùn)算符也可以應(yīng)用于非數(shù)值型操作數(shù),除了冪運(yùn)算符,它們只分兩個(gè)優(yōu)先級,即乘法類運(yùn)算和加法類運(yùn)算。
m_expr ::=
u_expr
|
m_expr
"*"
u_expr
|
m_expr
"//"
u_expr
|
m_expr
"/"
u_expr
|
m_expr
"%"
u_expr
a_expr ::=
m_expr
|
a_expr
"+"
m_expr
|
a_expr
"-"
m_expr
The * (multiplication) operator yields the product of its arguments. The
arguments must either both be numbers, or one argument must be an integer and
the other must be a sequence. In the former case, the numbers are converted to a
common type and then multiplied together. In the latter case, sequence
repetition is performed; a negative repetition factor yields an empty sequence.
* (乘)運(yùn)算符計(jì)算其操作數(shù)的乘積。要么兩個(gè)參數(shù)的類型都是數(shù)值型,要么一個(gè)是整數(shù)另一個(gè)是有序類型。第一種情況下,數(shù)值參數(shù)先被轉(zhuǎn)換成通用類型然后計(jì)算乘積。后一種情況會重復(fù)連接有序類型對象。一個(gè)負(fù)重復(fù)因子會產(chǎn)生一個(gè)空有序類型對象。
The / (division) and // (floor division) operators yield the quotient of
their arguments. The numeric arguments are first converted to a common type.
Integer division yields a float, while floor division of integers results in an
integer; the result is that of mathematical division with the ‘floor’ function
applied to the result. Division by zero raises the
ZeroDivisionError
exception.
/ (除)和 // (整除)運(yùn)算符生成參數(shù)的商。數(shù)值型參數(shù)首先被轉(zhuǎn)換成通用類型,整數(shù)除法的計(jì)算結(jié)果會產(chǎn)生一個(gè)浮點(diǎn)類型的結(jié)果,而整除操作則返回整數(shù)結(jié)果,即 ‘floor’ 函數(shù)做數(shù)學(xué)計(jì)算的結(jié)果。除以零會引發(fā)
ZeroDivisionError
異常。
The % (modulo) operator yields the remainder from the division of the first
argument by the second. The numeric arguments are first converted to a common
type. A zero right argument raises the
ZeroDivisionError
exception. The
arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34
(since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a
result with the same sign as its second operand (or zero); the absolute value of
the result is strictly smaller than the absolute value of the second operand
[1]
.
% (模)運(yùn)算符計(jì)算第一個(gè)參數(shù)除以第二參數(shù)得到的余數(shù)。數(shù)值型參數(shù)首先被轉(zhuǎn)換成通用類型,右面的參數(shù)為零會引發(fā)
ZeroDivisionError
異常。參數(shù)可以是浮點(diǎn)數(shù),例如 3.14%0.7 等于 0.34 (因?yàn)?3.14 等于 4*0.7 + 0.34 )。模運(yùn)算符的結(jié)果一定與第二個(gè)參數(shù)的符號相同(或者為0),并且結(jié)果的絕對值一定小于第二個(gè)參數(shù)的絕對值。
The floor division and modulo operators are connected by the following
identity: x == (x//y)*y + (x%y). Floor division and modulo are also
connected with the built-in function
divmod()
: divmod(x, y) == (x//y,
x%y).
[2]
.
整除和取模運(yùn)算可以用以下等式聯(lián)系起來: x == (x//y)*y + (x%y) 。整除和模運(yùn)算也可以用內(nèi)置函數(shù)
divmod()
,即 divmod(x, y) == (x//y,
x%y) 。
In addition to performing the modulo operation on numbers, the % operator is
also overloaded by string objects to perform old-style string formatting (also
known as interpolation). The syntax for string formatting is described in the
Python Library Reference, section
Old String Formatting Operations
.
除了執(zhí)行數(shù)字上的模運(yùn)算, % 運(yùn)算符也被字符串類型重載為舊風(fēng)格的字符串格式化(也稱為interpolation)。字符串格式化的語法在Python庫參考(Python Library Reference)中介紹,見
Old String Formatting Operations
。
The floor division operator, the modulo operator, and the
divmod()
function are not defined for complex numbers. Instead, convert to a floating
point number using the
abs()
function if appropriate.
整除、模運(yùn)算符和
divmod()
函數(shù)都不能操作復(fù)數(shù)。但可以在需要的時(shí)候用
abs()
函數(shù)將它們轉(zhuǎn)換成浮點(diǎn)數(shù)。
The + (addition) operator yields the sum of its arguments. The arguments
must either both be numbers or both sequences of the same type. In the former
case, the numbers are converted to a common type and then added together. In
the latter case, the sequences are concatenated.
+ (加)運(yùn)算符計(jì)算參數(shù)的和,參數(shù)要么必須都是數(shù)值型,或者都是相同類型的有序類型對象。對于前一種情況,它們先被轉(zhuǎn)換成通用類型然后相加。后一種情況下,所有有序類型對象都會被連接起來。
The - (subtraction) operator yields the difference of its arguments. The
numeric arguments are first converted to a common type.
- (減)計(jì)算參數(shù)的差,數(shù)值型的參數(shù)首先被轉(zhuǎn)換成通用類型。
5.7. 移位運(yùn)算(Shifting operations)
¶
The shifting operations have lower priority than the arithmetic operations:
移位運(yùn)算符的優(yōu)先級比算術(shù)運(yùn)算符低。
shift_expr ::=
a_expr
|
shift_expr
( ">" )
a_expr
These operators accept integers as arguments. They shift the first argument to
the left or right by the number of bits given by the second argument.
這些運(yùn)算符接受整數(shù)作為參數(shù)。它們將第一個(gè)參數(shù)向左或向右移動第二個(gè)參數(shù)指出的位數(shù)。
A right shift by n bits is defined as division by pow(2,n). A left shift
by n bits is defined as multiplication with pow(2,n).
右移 n 位可以定義為除以 pow(2,n) 。左移 n 位可以定義為乘以 pow(2,n) 。
5.8. 二元位操作運(yùn)算(Binary bitwise operations)
¶
Each of the three bitwise operations has a different priority level:
移位運(yùn)算符的優(yōu)先級各不相同:
and_expr ::=
shift_expr
|
and_expr
"&"
shift_expr
xor_expr ::=
and_expr
|
xor_expr
"^"
and_expr
or_expr ::=
xor_expr
|
or_expr
"|"
xor_expr
The & operator yields the bitwise AND of its arguments, which must be
integers.
& 運(yùn)算符生成參數(shù)的比特級 AND 運(yùn)算,參數(shù)必須是整數(shù)。
The ^ operator yields the bitwise XOR (exclusive OR) of its arguments, which
must be integers.
^ 運(yùn)算符生成參數(shù)的比特級 XOR 運(yùn)算(排斥或),參數(shù)必須是整數(shù)。
The | operator yields the bitwise (inclusive) OR of its arguments, which
must be integers.
| 運(yùn)算符生成參數(shù)的比特級 OR 運(yùn)算(包容或),參數(shù)必須是整數(shù)。
5.9. 比較運(yùn)算(Comparisons)
¶
Unlike C, all comparison operations in Python have the same priority, which is
lower than that of any arithmetic, shifting or bitwise operation. Also unlike
C, expressions like a b c have the interpretation that is conventional
in mathematics:
與C語言不同,Python中所有比較運(yùn)算符具有相同的優(yōu)先級,但比所有算術(shù)運(yùn)算符、移位運(yùn)算符和位運(yùn)算符都低,并且,不像C語言,表達(dá)式 a b c 與其數(shù)學(xué)含義相同。
comparison ::=
or_expr
(
comp_operator
or_expr
)*
comp_operator ::= "" | "==" | ">=" | "
Comparisons yield boolean values: True or False.
比較運(yùn)算符會生成布爾值 True 和 False 。
Comparisons can be chained arbitrarily, e.g., x y z is equivalent to
x y and y z, except that y is evaluated only once (but in both
cases z is not evaluated at all when x y is found to be false).
比較操作可以任意連接,例如, x y z 等價(jià)于 x y and y z ,除了 y 只會求值一次(但在這兩種情況下,都是只要發(fā)現(xiàn) x y 為假, z 就不會被求值了)。
Formally, if a, b, c, ..., y, z are expressions and op1, op2, ...,
opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent
to a op1 b and b op2 c and ... y opN z, except that each expression is
evaluated at most once.
形式上講,如果 a , b , c , ..., y , z 為表達(dá)式, op1 , op2 , ..., opN 為比較運(yùn)算符,則 a op1 b op2 c ...y opN z 等價(jià)于 a op1 b and b op2 c and ... y opN z ,除了每個(gè)表達(dá)式最多只求值一次。
Note that a op1 b op2 c doesn’t imply any kind of comparison between a and
c, so that, e.g., x y > z is perfectly legal (though perhaps not
pretty).
注意 a op1 b op2 c 并沒有隱式地規(guī)定 a 和 c 之間的比較運(yùn)算種類,所以 x y > z 是完全合法的(雖然不太美觀)。
The operators , >, ==, >=, , and != compare the
values of two objects. The objects need not have the same type. If both are
numbers, they are converted to a common type. Otherwise, the == and !=
operators always consider objects of different types to be unequal, while the
, >, >= and operators raise a
TypeError
when
comparing objects of different types that do not implement these operators for
the given pair of types. You can control comparison behavior of objects of
non-built-in types by defining rich comparison methods like
__gt__()
,
described in section
基本定制(Basic customization)
.
運(yùn)算符 、 > 、 == 、 >= 、 和 != 比較兩個(gè)對象的值,它們不需要具有相同的的類型。如果兩者都是數(shù)值型的,它們都先轉(zhuǎn)換成通用類型。否則, == 和 != 會把不同類型的值始終看成是不相等的,而在沒有實(shí)現(xiàn)不同類型對象間比較的運(yùn)算時(shí), 、 > 、 >= 和 則會拋出異常
TypeError
?梢酝ㄟ^定義在
基本定制(Basic customization)
一節(jié)中定義的厚比較方法(如
__gt__()
)定制對象的比較行為。
Comparison of objects of the same type depends on the type:
相同類型間對象的比較行為依賴于類型:
- Numbers are compared arithmetically.
數(shù)值型按大小比較。
- The values float('NaN') and Decimal('NaN') are special.
The are identical to themselves, x is x but are not equal to themselves,
x != x. Additionally, comparing any value to a not-a-number value
will return False. For example, both 3 float('NaN') and
float('NaN') 3 will return False.
值 float('NaN') 和 Decimal('NaN') 比較特殊。它們與自己完全相同,即 x is x 。但與自身并不相等,即 x != x 。另外,將任何值與非數(shù)字值比較都會返回 False ,例如, 3 float('NaN') 和 float('NaN') 3 都會返回 False 。
- Bytes objects are compared lexicographically using the numeric values of their
elements.
字節(jié)序列對象通過元素的數(shù)字值按字典序比較。
- Strings are compared lexicographically using the numeric equivalents (the
result of the built-in function
ord()
) of their characters.
[3]
String
and bytes object can’t be compared!
串按字典序進(jìn)行數(shù)學(xué)相等比較(每個(gè)字符的序數(shù)用內(nèi)置函數(shù)
ord()
得到)。字符串和字符序列不能相互比較!
- Tuples and lists are compared lexicographically using comparison of
corresponding elements. This means that to compare equal, each element must
compare equal and the two sequences must be of the same type and have the same
length.
元組和按列表字典序通過比較對應(yīng)的項(xiàng)進(jìn)行比較。因此“相等”意味著兩者的每個(gè)元素必須是相等的,兩個(gè)有序類型必須是相同類型的,并且長度相同。
If not equal, the sequences are ordered the same as their first differing
elements. For example, [1,2,x] [1,2,y] has the same value as
x y. If the corresponding element does not exist, the shorter
sequence is ordered first (for example, [1,2] [1,2,3]).
如果不相等,有序類型將按第一個(gè)不同元素確定順序。例如, [1,2,x] [1,2,y] 與 x y 相等。如果對應(yīng)元素不存在,則短些的有序類型排在前面,例如, [1,2] [1,2,3] 。
- Mappings (dictionaries) compare equal if and only if their sorted (key,
value) lists compare equal.
[4]
Outcomes other than equality are resolved
consistently, but are not otherwise defined.
[5]
映射(字典)相等,當(dāng)且僅當(dāng)其排序后 (key, value) 列表比較相等。這類相等不同于通常意義上的相等,只解決了一致性的問題,但還沒有定義其它的比較方法。
- Sets and frozensets define comparison operators to mean subset and superset
tests. Those relations do not define total orderings (the two sets {1,2}
and {2,3} are not equal, nor subsets of one another, nor supersets of one
another). Accordingly, sets are not appropriate arguments for functions
which depend on total ordering. For example,
min()
,
max()
, and
sorted()
produce undefined results given a list of sets as inputs.
集合和凍結(jié)集合(frozenset)將比較操作符定義成判斷是否為真子集和超集測試的操作。這種關(guān)系并沒有定義集合間的順序(例如, {1,2} 與 {2,3} 并不相等,同時(shí)也相互不為各自的真子集和超集 )。因此,不應(yīng)該把集合作為參數(shù)傳遞給行為依賴于參數(shù)比較結(jié)果的函數(shù)。例如函數(shù)
min()
、
max()
和
sorted()
在使用集合作為參數(shù)時(shí)會產(chǎn)生未定義的結(jié)果。
- Most other objects of built-in types compare unequal unless they are the same
object; the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one execution of a
program.
大多數(shù)其它內(nèi)置類型對象的比較,如果對象不同結(jié)果就是不等的。對象間哪個(gè)大,哪個(gè)小是不可以預(yù)知的,但相同程序的比較結(jié)果是前后一致的。
Comparison of objects of the differing types depends on whether either
of the types provide explicit support for the comparison. Most numeric types
can be compared with one another, but comparisons of
float
and
Decimal are not supported to avoid the inevitable confusion arising
from representation issues such as float('1.1') being inexactly represented
and therefore not exactly equal to Decimal('1.1') which is. When
cross-type comparison is not supported, the comparison method returns
NotImplemented. This can create the illusion of non-transitivity between
supported cross-type comparisons and unsupported comparisons. For example,
Decimal(2) == 2 and 2 == float(2)` but Decimal(2) != float(2).
不同類型對象間的比較行為取決于是否有任何一個(gè)類型提供了對這種比較的顯式支持。大多數(shù)數(shù)值型類型之間可以互相比較,但不支持
float
與 Decimal 的比較,以避免無可規(guī)避地表達(dá)上的混淆,例如 float('1.1') 是不精確的,因而不會與 Decimal('1.1') 精確相等。在不支持交叉類型比較時(shí),就會返回 NotImplemented 。注意,這會造成一種“支持交叉類型比較”和“不支持交叉類型比較”間的不可傳遞性的表象,例如,``Decimal(2) == 2`` 并且 2 == float(2)` 但 Decimal(2) != float(2) 。
The operators
in
and
not in
test for membership. x in
s evaluates to true if x is a member of s, and false otherwise. x not
in s returns the negation of x in s. All built-in sequences and set types
support this as well as dictionary, for which
in
tests whether a the
dictionary has a given key. For container types such as list, tuple, set,
frozenset, dict, or collections.deque, the expression x in y is equivalent
to any(x is e or x == e for val e in y).
in 運(yùn)算符和 not in 運(yùn)算符用于測試成員資格。如果 x 是 s 的成員,那么 x in s 的結(jié)果為真,否則為假。 x not in s 的結(jié)果與上相反。所有內(nèi)置有序類型和集合類型、以及字典都支持這種運(yùn)算,字典的
in
會測試左操作是不是它的鍵。對于容器類型,例如列表、元組、集合和凍結(jié)集合、字典或者其它c(diǎn)ollection,表達(dá)式 x in y 等價(jià)于 any(x is e or x == e for val e in y) 。
For the string and bytes types, x in y is true if and only if x is a
substring of y. An equivalent test is y.find(x) != -1. Empty strings are
always considered to be a substring of any other string, so "" in "abc" will
return True.
對于字符串和字節(jié)序列類型, x in y 當(dāng)且僅當(dāng) x 是 y 的子串。一個(gè)等價(jià)的測試是 y.find(x) != -1 ?沾徽J(rèn)為是所有字符串的子串,所以 "" in "abc" 會返回 True 。
For user-defined classes which define the
__contains__()
method, x in
y is true if and only if y.__contains__(x) is true.
對于定義了
__contains__()
方法的用戶定義類, x in y 為真僅當(dāng) y.__contains_(x) 為真。
For user-defined classes which do not define
__contains__()
and do define
__getitem__()
, x in y is true if and only if there is a non-negative
integer index i such that x == y, and all lower integer indices do not
raise
IndexError
exception. (If any other exception is raised, it is as
if
in
raised that exception).
如果用戶定義類沒有定義
__contains__()
方法,但定義了
__getitem__()
方法, x in y 為真,當(dāng)且僅當(dāng)存在一個(gè)非負(fù)的索引 i ,使得 x == y 滿足,并且所有小于該數(shù)的索引不能引發(fā)
IndexError
異常(如果引發(fā)了任何其它異常,就等同于是該運(yùn)算符引發(fā)的一樣)。
The operator
not in
is defined to have the inverse true value of
in
.
運(yùn)算符
not in
與運(yùn)算符
in
有相反的結(jié)果。
The operators
is
and
is not
test for object identity: x
is y is true if and only if x and y are the same object. x is not y
yields the inverse truth value.
[6]
運(yùn)算符
is
和
is not
測試對象標(biāo)識: x is y 為真,當(dāng)且僅當(dāng) x 和 y 是相同的對象。 x is not y 可以得到相反的結(jié)果。
5.10. 布爾運(yùn)算(Boolean operations)
¶
Boolean operations have the lowest priority of all Python operations:
布爾運(yùn)算符在所有Python運(yùn)算符中優(yōu)先級最低:
expression ::=
conditional_expression
|
lambda_form
expression_nocond ::=
or_test
|
lambda_form_nocond
conditional_expression ::=
or_test
["if"
or_test
"else"
expression
]
or_test ::=
and_test
|
or_test
"or"
and_test
and_test ::=
not_test
|
and_test
"and"
not_test
not_test ::=
comparison
| "not"
not_test
In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
False, None, numeric zero of all types, and empty strings and containers
(including strings, tuples, lists, dictionaries, sets and frozensets). All
other values are interpreted as true. User-defined objects can customize their
truth value by providing a
__bool__()
method.
在布爾運(yùn)算的上下文里,以及控制流語句所使用的表達(dá)式中,以下值解釋為假: False , None ,所有類型的數(shù)值零,空字符串和空容器對象(包括字符串、元組、列表、字典、集合和凍結(jié)集合)。所有其它值解釋為真。用戶定義類型可以通過定義
__bool__()
定制其真值類型。
The operator
not
yields True if its argument is false, False
otherwise.
如果運(yùn)算符
not
的參數(shù)為假,它返回 True ,否則返回 False 。
The expression x if C else y first evaluates C (not x); if C is
true, x is evaluated and its value is returned; otherwise, y is evaluated
and its value is returned.
表達(dá)式 x if C else y 會首先求 C ( 不是 x )的值;如果 C 為真,就求 x 的值并返回之,否則求 y 的值并返回之。
The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is returned.
表達(dá)式 x and y 首先計(jì)算 x ;如果 x 為假,就返回它的值,否則就計(jì)算 y 的值并返回其結(jié)果。
The expression x or y first evaluates x; if x is true, its value is
returned; otherwise, y is evaluated and the resulting value is returned.
表達(dá)式 x or y 首先計(jì)算 x ;如果 x 為真,就返回它的值,否則就計(jì)算 y 的值并返回其結(jié)果。
(Note that neither
and
nor
or
restrict the value and type
they return to False and True, but rather return the last evaluated
argument. This is sometimes useful, e.g., if s is a string that should be
replaced by a default value if it is empty, the expression s or 'foo' yields
the desired value. Because
not
has to invent a value anyway, it does
not bother to return a value of the same type as its argument, so e.g., not
'foo' yields False, not ''.)
(注意 and 和 or 都沒有限制返回的值和類型必須是 False 或 True ,而是最后一個(gè)求值的表達(dá)式的結(jié)果。在某些情況下這特別有用,例如,如果 s 是一個(gè)如果為空就應(yīng)該被替換成默認(rèn)值的字符串,表達(dá)式 s or ’foo’ 就會得到希望的結(jié)果。因?yàn)?not 也必須生成一個(gè)值,它的返回值類型不必與其參數(shù)的類型相同。這樣,例如, not ’foo’ 會返回 False ,而不是 '' 。)
5.11. Lambdas
¶
lambda_form ::= "lambda" [
parameter_list
]:
expression
lambda_form_nocond ::= "lambda" [
parameter_list
]:
expression_nocond
Lambda forms (lambda expressions) have the same syntactic position as
expressions. They are a shorthand to create anonymous functions; the expression
lambda arguments: expression yields a function object. The unnamed object
behaves like a function object defined with :
Lambda型(lambda表達(dá)式)在語法上與表達(dá)式有相同的位置。這是一個(gè)創(chuàng)建匿名函數(shù)的快捷方法,表達(dá)式 lambda arguments: expression 會生成一個(gè)函數(shù)對象,這個(gè)無名對象的行為與以下函數(shù)行為基本相同:
def (arguments):
return expression
See section
函數(shù)定義(Function definitions)
for the syntax of parameter lists. Note that
functions created with lambda forms cannot contain statements or annotations.
對于參數(shù)表語法,參見
函數(shù)定義(Function definitions)
。注意由lambda型創(chuàng)建的函數(shù)不能包括語句或者注解(annotation)。
5.12. 表達(dá)式列表(Expression lists)
¶
expression_list ::=
expression
( ","
expression
)* [","]
An expression list containing at least one comma yields a tuple. The length of
the tuple is the number of expressions in the list. The expressions are
evaluated from left to right.
表達(dá)式表是一個(gè)包括至少一個(gè)逗號的元組,它的長度是其中表達(dá)式的個(gè)數(shù),其中的表達(dá)式從左到右按順序求值。
The trailing comma is required only to create a single tuple (a.k.a. a
singleton); it is optional in all other cases. A single expression without a
trailing comma doesn’t create a tuple, but rather yields the value of that
expression. (To create an empty tuple, use an empty pair of parentheses:
().)
只有在創(chuàng)建單元素元組時(shí)(又稱為 singleton )時(shí)才需要最后的逗號,否則它是可選的。沒有后綴逗號的單獨(dú)表達(dá)式不會創(chuàng)建元組,但仍會計(jì)算該表達(dá)式的值(可以使用一對空括號 () 創(chuàng)建一個(gè)空元組)。
5.13. 求值順序(Evaluation order)
¶
Python evaluates expressions from left to right. Notice that while evaluating
an assignment, the right-hand side is evaluated before the left-hand side.
Python自左至右的對表達(dá)式求值,但請注意賦值時(shí)右側(cè)的求值先于左側(cè)。
In the following lines, expressions will be evaluated in the arithmetic order of
their suffixes:
在以下行中,表達(dá)式的求值會按其數(shù)字后綴順序進(jìn)行:
expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2
5.14. 總結(jié)(Summary)
¶
The following table summarizes the operator precedences in Python, from lowest
precedence (least binding) to highest precedence (most binding). Operators in
the same box have the same precedence. Unless the syntax is explicitly given,
operators are binary. Operators in the same box group left to right (except for
comparisons, including tests, which all have the same precedence and chain from
left to right — see section
比較運(yùn)算(Comparisons)
— and exponentiation, which
groups from right to left).
下表總結(jié)了Python中運(yùn)算符的優(yōu)先級,從最低優(yōu)先級(最弱的綁定)到最高優(yōu)先級(最強(qiáng)的綁定)。同一格子中的運(yùn)算符具有相同的優(yōu)先級。如果沒有
特殊的語法規(guī)定,運(yùn)算符是二元的。同一格子內(nèi)的運(yùn)算符都從左至右結(jié)合(比較運(yùn)算符和成員資格測試運(yùn)算符是個(gè)例外,它們有相同的優(yōu)先級并可以從左到右串接起
來 —— 參見
比較運(yùn)算(Comparisons)
,此外,冪運(yùn)算符也是從右至左結(jié)合的)。
Operator
Description
lambda
Lambda expression
or
Boolean OR
and
Boolean AND
not
x
Boolean NOT
in
,
not
in
,
is
,
is not
, ,
, >, >=, !=, ==
Comparisons, including membership
tests and identity tests,
|
Bitwise OR
^
Bitwise XOR
&
Bitwise AND
, >>
Shifts
+, -
Addition and subtraction
*, /, //, %
Multiplication, division, remainder
+x, -x, ~x
Positive, negative, bitwise NOT
**
Exponentiation
[7]
x[index], x[index:index],
x(arguments...), x.attribute
Subscription, slicing,
call, attribute reference
(expressions...),
[expressions...],
{key:datum...},
Binding or tuple display,
list display,
dictionary display,
運(yùn)算符
描述
lambda
Lambda 表達(dá)式
or
布爾 OR
and
布爾 AND
not
x
布爾 NOT
in
,
not
in
,
is
,
is not
, ,
, >, >=, !=, ==
比較操作,包括成員資格測試和標(biāo)識測試
|
比特級 OR
^
比特級 XOR
&
比特級 AND
, >>
移位
+, -
加減操作
*, /, //, %
乘除,求余數(shù)
+x, -x, ~x
正、負(fù)和比特級 NOT
**
求冪
x[index], x[index:index],
x(arguments...), x.attribute
下標(biāo)、片斷、調(diào)用和屬性引用
(expressions...),
[expressions...],
{key:datum...},
綁定或者元組的 display
列表的 display,
字典的 display,
腳注(Footnotes)
[1]
While abs(x%y) abs(y) is true mathematically, for floats it may not be
true numerically due to roundoff. For example, and assuming a platform on which
a Python float is an IEEE 754 double-precision number, in order that -1e-100 %
1e100 have the same sign as 1e100, the computed result is -1e-100 +
1e100, which is numerically exactly equal to 1e100. Function fmod()
in the
math
module returns a result whose sign matches the sign of the
first argument instead, and so returns -1e-100 in this case. Which approach
is more appropriate depends on the application.
雖然在數(shù)學(xué)上 abs(x%y) abs(y) 一定為真,但可能因?yàn)樯崛氲脑驅(qū)е略诔绦蚶镞@個(gè)表達(dá)式結(jié)果不為真。例如,假定某個(gè)平臺使用IEEE 754的雙精度浮點(diǎn)數(shù)表示Python浮點(diǎn)數(shù),這樣 -1e-100 % 1e100 與 1e100 的符號相同,且計(jì)算結(jié)果為 -1e-100 + 1e100 ,它在數(shù)值上完全等于 1e100 。而模塊
math
中的函數(shù) fmod() 返回結(jié)果的符號與第一個(gè)參數(shù)的相同,返回值是 -1e-100 。哪種方法更合適取決于應(yīng)用程序。
[2]
If x is very close to an exact integer multiple of y, it’s possible for
x//y to be one larger than (x-x%y)//y due to rounding. In such
cases, Python returns the latter result, in order to preserve that
divmod(x,y)[0] * y + x % y be very close to x.
如果 x 非常接近于 y 的倍數(shù),那么因?yàn)樯崛氲脑?x//y 有可能大于 (x-x%y)//y 。這時(shí),Python會返回后者作為結(jié)果,以防止 divmod(x,y)[0] * y + x % y 過于接近 x 。
[3]
While comparisons between strings make sense at the byte level, they may
be counter-intuitive to users. For example, the strings "\u00C7" and
"\u0327\u0043" compare differently, even though they both represent the
same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare
strings in a human recognizable way, compare using
unicodedata.normalize()
.
雖然字符串的比較就是字節(jié)意義上比較,但它們對于用戶來說有可能與直覺沖突。例如, "\u00C7" 與 "\u0327\u0043" 比較結(jié)果是不同,即使它是其實(shí)是相同的unicode字符(大寫拉丁字母C和一個(gè)下劃線)。通常意義上的比較,應(yīng)該使用
unicodedata.normalize()
。
[4]
The implementation computes this efficiently, without constructing lists
or sorting.
實(shí)現(xiàn)可能采用某些高效率的方法,并不一定需要構(gòu)造這個(gè)列表或者排序之。
[5]
Earlier versions of Python used lexicographic comparison of the sorted (key,
value) lists, but this was very expensive for the common case of comparing
for equality. An even earlier version of Python compared dictionaries by
identity only, but this caused surprises because people expected to be able
to test a dictionary for emptiness by comparing it to {}.
之前的Python使用排序后的 (key, value) 列表進(jìn)行字典序的比較,但這在進(jìn)行相等比較時(shí)代價(jià)非常高。某個(gè)早期版本的Python甚至直接使用對象標(biāo)識比較字典對象,但是這會導(dǎo)致不良的行為,因?yàn)橛脩粝Mㄟ^與 {} 比較來判斷一個(gè)字典是否為空。
[6]
Due to automatic garbage-collection, free lists, and the dynamic nature of
descriptors, you may notice seemingly unusual behaviour in certain uses of
the
is
operator, like those involving comparisons between instance
methods, or constants. Check their documentation for more info.
因?yàn)樽詣永占琭ree list和描述符的動態(tài)本質(zhì)的緣故,你可能會在某些情況使用
is
運(yùn)算符發(fā)現(xiàn)一些不尋常的行為,例如在實(shí)例方法或者常量之間比較時(shí)。更多信息可以去查看它們的文檔。
[7]
The power operator ** binds less tightly than an arithmetic or
bitwise unary operator on its right, that is, 2**-1 is 0.5.
冪運(yùn)算符 ** 比其右面的算術(shù)運(yùn)算符和一元位運(yùn)算符優(yōu)先級低,所以, 2**-1 的結(jié)果是 0.5 。
本文來自ChinaUnix博客,如果查看原文請點(diǎn):http://blog.chinaunix.net/u1/42957/showart_2137539.html |
|