### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](simple_stmts.xhtml "7. 簡單語句") |
- [上一頁](import.xhtml "5. 導入系統") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 語言參考](index.xhtml) ?
- $('.inline-search').show(0); |
# 6. 表達式
本章將解釋 Python 中組成表達式的各種元素的的含義。
**語法注釋:** 在本章和后續章節中,會使用擴展 BNF 標注來描述語法而不是詞法分析。 當(某種替代的)語法規則具有如下形式
```
name ::= `othername`
```
并且沒有給出語義,則這種形式的 `name` 在語法上與 `othername` 相同。
## 6.1. 算術轉換
當對下述某個算術運算符的描述中使用了“數值參數被轉換為普通類型”這樣的說法,這意味著內置類型的運算符實現采用了如下作用方式:
- 如果任一參數為復數,另一參數會被轉換為復數;
- 否則,如果任一參數為浮點數,另一參數會被轉換為浮點數;
- 否則,兩者應該都為整數,不需要進行轉換。
某些附加規則會作用于特定運算符(例如,字符串作為 '%' 運算符的左運算參數)。 擴展必須定義它們自己的轉換行為。
## 6.2. 原子
“原子”指表達式的最基本構成元素。 最簡單的原子是標識符和字面值。 以圓括號、方括號或花括號包括的形式在語法上也被歸類為原子。 原子的句法為:
```
atom ::= identifier | literal | enclosure
enclosure ::= parenth_form | list_display | dict_display | set_display
| generator_expression | yield_atom
```
### 6.2.1. 標識符(名稱)
作為原子出現的標識符叫做名稱。 請參看 [標識符和關鍵字](lexical_analysis.xhtml#identifiers) 一節了解其詞法定義,以及 [命名與綁定](executionmodel.xhtml#naming) 獲取有關命名與綁定的文檔。
當名稱被綁定到一個對象時,對該原子求值將返回相應對象。 當名稱未被綁定時,嘗試對其求值將引發 [`NameError`](../library/exceptions.xhtml#NameError "NameError") 異常。
**私有名稱轉換:** 當以文本形式出現在類定義中的一個標識符以兩個或更多下劃線開頭并且不以兩個或更多下劃線結尾,它會被視為該類的 *私有名稱*。 私有名稱會在為其生成代碼之前被轉換為一種更長的形式。 轉換時會插入類名,移除打頭的下劃線再在名稱前增加一個下劃線。 例如,出現在一個名為 `Ham` 的類中的標識符 `__spam` 會被轉換為 `_Ham__spam`。 這種轉換獨立于標識符所使用的相關句法。 如果轉換后的名稱太長(超過 255 個字符),可能發生由具體實現定義的截斷。 如果類名僅由下劃線組成,則不會進行轉換。
### 6.2.2. 字面值
Python 支持字符串和字節串字面值,以及幾種數字字面值:
```
literal ::= stringliteral | bytesliteral
| integer | floatnumber | imagnumber
```
對字面值求值將返回一個該值所對應類型的對象(字符串、字節串、整數、浮點數、復數)。 對于浮點數和虛數(復數)的情況,該值可能為近似值。 詳情參見 [字面值](lexical_analysis.xhtml#literals)。
所有字面值都對應與不可變數據類型,因此對象標識的重要性不如其實際值。 多次對具有相同值的字面值求值(不論是發生在程序文本的相同位置還是不同位置)可能得到相同對象或是具有相同值的不同對象。
### 6.2.3. 帶圓括號的形式
帶圓括號的形式是包含在圓括號中的可選表達式列表。
```
parenth_form ::= "(" [starred_expression] ")"
```
帶圓括號的表達式列表將返回該表達式列表所產生的任何東西:如果該列表包含至少一個逗號,它會產生一個元組;否則,它會產生該表達式列表所對應的單一表達式。
An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).
請注意元組并不是由圓括號構建,實際起作用的是逗號操作符。 例外情況是空元組,這時圓括號 *才是* 必須的 --- 允許在表達式中使用不帶圓括號的 "空" 會導致歧義,并會造成常見輸入錯誤無法被捕獲。
### 6.2.4. 列表、集合與字典的顯示
為了構建列表、集合或字典,Python 提供了名為“顯示”的特殊句法,每個類型各有兩種形式:
- 第一種是顯式地列出容器內容
- 第二種是通過一組循環和篩選指令計算出來,稱為 *推導式*。
推導式的常用句法元素為:
```
comprehension ::= expression comp_for
comp_for ::= ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter ::= comp_for | comp_if
comp_if ::= "if" expression_nocond [comp_iter]
```
推導式的結構是一個單獨表達式后面加至少一個 `for` 子句以及零個或更多個 `for` 或 `if` 子句。 在這種情況下,新容器的元素產生方式是將每個 `for` 或 `if` 子句視為一個代碼塊,按從左至右的順序嵌套,然后每次到達最內層代碼塊時就對表達式進行求值以產生一個元素。
不過,除了最左邊 `for` 子句中的可迭代表達式,推導式是在另一個隱式嵌套的作用域內執行的。 這能確保賦給目標列表的名稱不會“泄露”到外層的作用域。
最左邊 `for` 子句中的可迭代表達式會直接在外層作用域中被求值,然后作為一個參數被傳給隱式嵌套的作用域。 后續的 `for` 子句以及最左側 `for` 子句中的任何篩選條件不能在外層作用域中被求值,因為它們可能依賴于從最左側可迭代對象中獲得的值。 例如: `[x*y for x in range(10) for y in range(x, x+10)]`.
為了確保推導式得出的結果總是一個類型正確的容器,在隱式嵌套的作用域內禁止使用 `yield` 和 `yield from` 表達式 (在 Python 3.7 中,這樣的表達式會在編譯時引發 [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning"),在 Python 3.8+ 中它們將引發 [`SyntaxError`](../library/exceptions.xhtml#SyntaxError "SyntaxError"))。
從 Python 3.6 開始,在 [`async def`](compound_stmts.xhtml#async-def) 函數中可以使用 `async for` 子句來迭代 [asynchronous iterator](../glossary.xhtml#term-asynchronous-iterator)。 在 `async def` 函數中構建推導式可以通過在打頭的表達式后加上 `for` 或 `async for` 子句,也可能包含額外的 `for` 或 `async for` 子句,還可能使用 [`await`](#await) 表達式。 如果一個推導式包含 `async for` 子句或者 `await` 表達式,則被稱為 *異步推導式*。 異步推導式可以暫停執行它所在的協程函數。 另請參閱 [**PEP 530**](https://www.python.org/dev/peps/pep-0530) \[https://www.python.org/dev/peps/pep-0530\]。
3\.6 新版功能: 引入了異步推導式。
3\.7 版后已移除: `yield` and `yield from` 在隱式嵌套的作用域內已棄用。
### 6.2.5. 列表顯示
列表顯示是一個用方括號括起來的可能為空的表達式系列:
```
list_display ::= "[" [starred_list | comprehension] "]"
```
列表顯示會產生一個新的列表對象,其內容通過一系列表達式或一個推導式來指定。 當提供由逗號分隔的一系列表達式時,其元素會從左至右被求值并按此順序放入列表對象。 當提供一個推導式時,列表會根據推導式所產生的結果元素進行構建。
### 6.2.6. 集合顯示
集合顯示是用花括號標明的,與字典顯示的區別在于沒有冒號分隔的鍵和值:
```
set_display ::= "{" (starred_list | comprehension) "}"
```
集合顯示會產生一個新的可變集合對象,其內容通過一系列表達式或一個推導式來指定。 當提供由逗號分隔的一系列表達式時,其元素會從左至右被求值并加入到集合對象。 當提供一個推導式時,集合會根據推導式所產生的結果元素進行構建。
空集合不能用 `{}` 來構建;該字面值所構建的是一個空字典。
### 6.2.7. 字典顯示
字典顯示是一個用花括號括起來的可能為空的鍵/數據對系列:
```
dict_display ::= "{" [key_datum_list | dict_comprehension] "}"
key_datum_list ::= key_datum ("," key_datum)* [","]
key_datum ::= expression ":" expression | "**" or_expr
dict_comprehension ::= expression ":" expression comp_for
```
字典顯示會產生一個新的字典對象。
如果給出一個由逗號分隔的鍵/數據對序列,它們會從左至右被求值以定義字典的條目:每個鍵對象會被用作在字典中存放相應數據的鍵。 這意味著你可以在鍵/數據對序列中多次指定相同的鍵,最終字典的值將由最后一次給出的鍵決定。
雙星號 `**` 表示 *字典拆包*。 它的操作數必須是一個 [mapping](../glossary.xhtml#term-mapping)。 每個映射項被會加入新的字典。 后續的值會替代先前的鍵/數據對和先前的字典拆包所設置的值。
3\.5 新版功能: 拆包到字典顯示,最初由 [**PEP 448**](https://www.python.org/dev/peps/pep-0448) \[https://www.python.org/dev/peps/pep-0448\] 提出。
字典推導式與列表和集合推導式有所不同,它需要以冒號分隔的兩個表達式,后面帶上標準的 "for" 和 "if" 子句。 當推導式被執行時,作為結果的鍵和值元素會按它們的產生順序被加入新的字典。
對鍵取值類型的限制已列在之前的 [標準類型層級結構](datamodel.xhtml#types) 一節中。 (總的說來,鍵的類型應該為 [hashable](../glossary.xhtml#term-hashable),這就把所有可變對象都排除在外。) 重復鍵之間的沖突不會被檢測;指定鍵所保存的最后一個數據 (即在顯示中排最右邊的文本) 為最終有效數據。
### 6.2.8. 生成器表達式
生成器表達式是用圓括號括起來的緊湊形式生成器標注。
```
generator_expression ::= "(" expression comp_for ")"
```
生成器表達式會產生一個新的生成器對象。 其句法與推導式相同,區別在于它是用圓括號而不是用方括號或花括號括起來的。
在生成器表達式中使用的變量會在為生成器對象調用 [`__next__()`](#generator.__next__ "generator.__next__") 方法的時候以惰性方式被求值(即與普通生成器相同的方式)。 但是,最左側 `for` 子句內的可迭代對象是會被立即求值的,因此它所造成的錯誤會在生成器表達式被定義時被檢測到,而不是在獲取第一個值時才出錯。 后續的 `for` 子句以及最左側 `for` 子句內的任何篩選條件無法在外層作用域內被求值,因為它們可能會依賴于從最左側可迭代對象獲取的值。 例如: `(x*y for x in range(10) for y in range(x, x+10))`.
圓括號在只附帶一個參數的調用中可以被省略。 詳情參見 [調用](#calls) 一節。
為避免干擾到生成器表達式本身預期的操作,`yield` 和 `yield from` 表達式禁止在隱式定義的生成器中使用 (在 Python 3.7 中,這種表達式會在編譯時引發 [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning"),在 Python 3.8+ 中它們將引發 [`SyntaxError`](../library/exceptions.xhtml#SyntaxError "SyntaxError"))。
如果生成器表達式包含 `async for` 子句或 [`await`](#await) 表達式,則稱為 *異步生成器表達式*。 異步生成器表達式會返回一個新的異步生成器對象,此對象屬于異步迭代器 (參見 [異步迭代器](datamodel.xhtml#async-iterators))。
3\.6 新版功能: 引入了異步生成器表達式。
在 3.7 版更改: 在 Python 3.7 之前,異步生成器表達式只能在 [`async def`](compound_stmts.xhtml#async-def) 協和中出現。 從 3.7 開始,任何函數都可以使用異步生成器表達式。
3\.7 版后已移除: `yield` and `yield from` 在隱式嵌套的作用域內已棄用。
### 6.2.9. yield 表達式
```
yield_atom ::= "(" yield_expression ")"
yield_expression ::= "yield" [expression_list | "from" expression]
```
yield 表達式在定義 [generator](../glossary.xhtml#term-generator) 函數或是 [asynchronous generator](../glossary.xhtml#term-asynchronous-generator) 的時候才會用到。 因此只能在函數定義的內部使用yield表達式。 在一個函數體內使用 yield 表達式會使這個函數變成一個生成器,并且在一個 [`async def`](compound_stmts.xhtml#async-def) 定義的函數體內使用 yield 表達式會讓協程函數變成異步的生成器。 比如說:
```
def gen(): # defines a generator function
yield 123
async def agen(): # defines an asynchronous generator function
yield 123
```
由于它們會對外層作用域造成附帶影響,`yield` 表達式不被允許作為用于實現推導式和生成器表達式的隱式定義作用域的一部分 (在 Python 3.7 中,此類表達式會在編譯時引發 [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning"),在 Python 3.8+ 中它們將引發 [`SyntaxError`](../library/exceptions.xhtml#SyntaxError "SyntaxError"))。
3\.7 版后已移除: yield 表達式在用于實現推導式和生成器表達式的隱式嵌套作用域中已棄用。
下面是對生成器函數的描述,異步生成器函數會在 [異步生成器函數](#asynchronous-generator-functions) 一節中單獨介紹。
當一個生成器函數被調用的時候,它返回一個迭代器,稱為生成器。然后這個生成器來控制生成器函數的執行。當這個生成器的某一個方法被調用的時候,生成器函數開始執行。這時會一直執行到第一個 yield 表達式,在此執行再次被掛起,給生成器的調用者返回 [`expression_list`](#grammar-token-expression-list) 的值。掛起后,我們說所有局部狀態都被保留下來,包括局部變量的當前綁定,指令指針,內部求值棧和任何異常處理的狀態。通過調用生成器的某一個方法,生成器函數繼續執行。此時函數的運行就和 yield 表達式只是一個外部函數調用的情況完全一致。恢復后 yield 表達式的值取決于調用的哪個方法來恢復執行。 如果用的是 [`__next__()`](#generator.__next__ "generator.__next__") (通常通過語言內置的 [`for`](compound_stmts.xhtml#for) 或是 [`next()`](../library/functions.xhtml#next "next") 來調用) 那么結果就是 [`None`](../library/constants.xhtml#None "None"). 否則,如果用 [`send()`](#generator.send "generator.send"), 那么結果就是傳遞給send方法的值。
所有這些使生成器函數與協程非常相似;它們 yield 多次,它們具有多個入口點,并且它們的執行可以被掛起。唯一的區別是生成器函數不能控制在它在 yield 后交給哪里繼續執行;控制權總是轉移到生成器的調用者。
在 [`try`](compound_stmts.xhtml#try) 結構中的任何位置都允許yield表達式。如果生成器在(因為引用計數到零或是因為被垃圾回收)銷毀之前沒有恢復執行,將調用生成器-迭代器的 [`close()`](#generator.close "generator.close") 方法. close 方法允許任何掛起的 [`finally`](compound_stmts.xhtml#finally) 子句執行。
當使用 `yield from <expr>` 時,它會將所提供的表達式視為一個子迭代器。 這個子迭代器產生的所有值都直接被傳遞給當前生成器方法的調用者。 通過 [`send()`](#generator.send "generator.send") 傳入的任何值以及通過 [`throw()`](#generator.throw "generator.throw") 傳入的任何異常如果有適當的方法則會被傳給下層迭代器。 如果不是這種情況,那么 [`send()`](#generator.send "generator.send") 將引發 [`AttributeError`](../library/exceptions.xhtml#AttributeError "AttributeError") 或 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError"),而 [`throw()`](#generator.throw "generator.throw") 將立即引發所傳入的異常。
When the underlying iterator is complete, the `value`attribute of the raised [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") instance becomes the value of the yield expression. It can be either set explicitly when raising [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration"), or automatically when the subiterator is a generator (by returning a value from the subgenerator).
> 在 3.3 版更改: 添加 `yield from <expr>` 以委托控制流給一個子迭代器。
當yield表達式是賦值語句右側的唯一表達式時,括號可以省略。
參見
[**PEP 255**](https://www.python.org/dev/peps/pep-0255) \[https://www.python.org/dev/peps/pep-0255\] - 簡單生成器在 Python 中加入生成器和 [`yield`](simple_stmts.xhtml#yield) 語句的提議。
[**PEP 342**](https://www.python.org/dev/peps/pep-0342) \[https://www.python.org/dev/peps/pep-0342\] - 通過增強型生成器實現協程增強生成器 API 和語法的提議,使其可以被用作簡單的協程。
[**PEP 380**](https://www.python.org/dev/peps/pep-0380) \[https://www.python.org/dev/peps/pep-0380\] - 委托給子生成器的語法The proposal to introduce the `yield_from` syntax, making delegation to subgenerators easy.
[**PEP 525**](https://www.python.org/dev/peps/pep-0525) \[https://www.python.org/dev/peps/pep-0525\] - 異步生成器通過給協程函數加入生成器功能對 [**PEP 492**](https://www.python.org/dev/peps/pep-0492) \[https://www.python.org/dev/peps/pep-0492\] 進行擴展的提議。
#### 6.2.9.1. 生成器-迭代器的方法
這個子小節描述了生成器迭代器的方法。 它們可被用于控制生成器函數的執行。
請注意在生成器已經在執行時調用以下任何方法都會引發 [`ValueError`](../library/exceptions.xhtml#ValueError "ValueError") 異常。
`generator.``__next__`()開始一個生成器函數的執行或是從上次執行的 yield 表達式位置恢復執行。 當一個生成器函數通過 [`__next__()`](#generator.__next__ "generator.__next__") 方法恢復執行時,當前的 yield 表達式總是取值為 [`None`](../library/constants.xhtml#None "None")。 隨后會繼續執行到下一個 yield 表達式,其 [`expression_list`](#grammar-token-expression-list) 的值會返回給 [`__next__()`](#generator.__next__ "generator.__next__") 的調用者。 如果生成器沒有產生下一個值就退出,則將引發 [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") 異常。
此方法通常是隱式地調用,例如通過 [`for`](compound_stmts.xhtml#for) 循環或是內置的 [`next()`](../library/functions.xhtml#next "next") 函數。
`generator.``send`(*value*)恢復執行并向生成器函數“發送”一個值。 *value* 參數將成為當前 yield 表達式的結果。 [`send()`](#generator.send "generator.send") 方法會返回生成器所產生的下一個值,或者如果生成器沒有產生下一個值就退出則會引發 [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration")。 當調用 [`send()`](#generator.send "generator.send") 來啟動生成器時,它必須以 [`None`](../library/constants.xhtml#None "None") 作為調用參數,因為這時沒有可以接收值的 yield 表達式。
`generator.``throw`(*type*\[, *value*\[, *traceback*\]\])在生成器暫停的位置引發 `type` 類型的異常,并返回該生成器函數所產生的下一個值。 如果生成器沒有產生下一個值就退出,則將引發 [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") 異常。 如果生成器函數沒有捕獲傳入的異常,或引發了另一個異常,則該異常會被傳播給調用者。
`generator.``close`()在生成器函數暫停的位置引發 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit")。 如果之后生成器函數正常退出、關閉或引發 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit") (由于未捕獲該異常) 則關閉并返回其調用者。 如果生成器產生了一個值,關閉會引發 [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError")。 如果生成器引發任何其他異常,它會被傳播給調用者。 如果生成器已經由于異常或正常退出則 [`close()`](#generator.close "generator.close") 不會做任何事。
#### 6.2.9.2. 示例
這里是一個簡單的例子,演示了生成器和生成器函數的行為:
```
>>> 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.
```
對于 `yield from` 的例子, 參見“Python 有什么新變化”中的 [PEP 380: Syntax for Delegating to a Subgenerator](../whatsnew/3.3.xhtml#pep-380)。
#### 6.2.9.3. 異步生成器函數
The presence of a yield expression in a function or method defined using [`async def`](compound_stmts.xhtml#async-def) further defines the function as an [asynchronous generator](../glossary.xhtml#term-asynchronous-generator) function.
當一個異步生成器函數被調用時,它會返回一個名為異步生成器對象的異步迭代器。 此對象將在之后控制該生成器函數的執行。 異步生成器對象通常被用在協程函數的 [`async for`](compound_stmts.xhtml#async-for) 語句中,類似于在 [`for`](compound_stmts.xhtml#for) 語句中使用生成器對象。
調用異步生成器的方法之一將返回 [awaitable](../glossary.xhtml#term-awaitable) 對象,執行會在此對象被等待時啟動。 到那時,執行將前往第一個 yield 表達式,在那里它會再次暫停,將 [`expression_list`](#grammar-token-expression-list) 的值返回給等待中的協程。 與生成器一樣,掛起意味著局部的所有狀態會被保留,包括局部變量的當前綁定、指令的指針、內部求值的堆棧以及任何異常處理的狀態。 當執行在等待異步生成器的方法返回下一個對象后恢復時,該函數可以從原狀態繼續進行,就仿佛 yield 表達式只是另一個外部調用。 恢復執行之后 yield 表達式的值取決于恢復執行所用的方法。 如果使用 [`__anext__()`](#agen.__anext__ "agen.__anext__") 則結果為 [`None`](../library/constants.xhtml#None "None")。 否則的話,如果使用 [`asend()`](#agen.asend "agen.asend") 則結果將是傳遞給該方法的值。
在異步生成器函數中,yield 表達式允許出現在 [`try`](compound_stmts.xhtml#try) 結構的任何位置。 但是,如果一個異步生成器在其被終結(由于引用計數達到零或被作為垃圾回收)之前未被恢復,則then a yield expression within a `try` 結構中的 yield 表達式可能導致掛起的 [`finally`](compound_stmts.xhtml#finally) 子句執行失敗。 在此情況下,應由運行該異步生成器的事件循環或任務調度器來負責調用異步生成器-迭代器的 [`aclose()`](#agen.aclose "agen.aclose") 方法并運行所返回的協程對象,從而允許任何掛起的 `finally` 子句得以執行。
為了能處理最終化,事件循環應該定義一個 *終結器* 函數,它接受一個異步生成器-迭代器且可能調用 [`aclose()`](#agen.aclose "agen.aclose") 并執行協程。 這個 *終結器* 可能通過調用 [`sys.set_asyncgen_hooks()`](../library/sys.xhtml#sys.set_asyncgen_hooks "sys.set_asyncgen_hooks") 來注冊。 當首次迭代時,異步生成器-迭代器將保存已注冊的 *終結器* 以便在最終化時調用。 有關For a reference example of a *終結器* 方法的參考示例請查看 [Lib/asyncio/base\_events.py](https://github.com/python/cpython/tree/3.7/Lib/asyncio/base_events.py) \[https://github.com/python/cpython/tree/3.7/Lib/asyncio/base\_events.py\] 中實現的 `asyncio.Loop.shutdown_asyncgens`。
`yield from <expr>` 表達式如果在異步生成器函數中使用會引發語法錯誤。
#### 6.2.9.4. 異步生成器-迭代器方法
這個子小節描述了異步生成器迭代器的方法,它們可被用于控制生成器函數的執行。
*coroutine* `agen.``__anext__`()Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with an [`__anext__()`](#agen.__anext__ "agen.__anext__")method, the current yield expression always evaluates to [`None`](../library/constants.xhtml#None "None") in the returned awaitable, which when run will continue to the next yield expression. The value of the [`expression_list`](#grammar-token-expression-list) of the yield expression is the value of the [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a [`StopAsyncIteration`](../library/exceptions.xhtml#StopAsyncIteration "StopAsyncIteration") exception, signalling that the asynchronous iteration has completed.
此方法通常是通過 [`async for`](compound_stmts.xhtml#async-for) 循環隱式地調用。
*coroutine* `agen.``asend`(*value*)返回一個可等待對象,它在運行時會恢復該異步生成器的執行。 與生成器的 [`send()`](#generator.send "generator.send") 方法一樣,此方法會“發送”一個值給異步生成器函數,其 *value* 參數會成為當前 yield 表達式的結果值。 [`asend()`](#agen.asend "agen.asend") 方法所返回的可等待對象將返回生成器產生的下一個值,其值為所引發的 [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration"),或者如果異步生成器沒有產生下一個值就退出則引發 [`StopAsyncIteration`](../library/exceptions.xhtml#StopAsyncIteration "StopAsyncIteration")。 當調用 [`asend()`](#agen.asend "agen.asend") 來啟動異步生成器時,它必須以 [`None`](../library/constants.xhtml#None "None") 作為調用參數,因為這時沒有可以接收值的 yield 表達式。
*coroutine* `agen.``athrow`(*type*\[, *value*\[, *traceback*\]\])Returns an awaitable that raises an exception of type `type` at the point where the asynchronous generator was paused, and returns the next value yielded by the generator function as the value of the raised [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") exception. If the asynchronous generator exits without yielding another value, a [`StopAsyncIteration`](../library/exceptions.xhtml#StopAsyncIteration "StopAsyncIteration") exception is raised by the awaitable. If the generator function does not catch the passed-in exception, or raises a different exception, then when the awaitable is run that exception propagates to the caller of the awaitable.
*coroutine* `agen.``aclose`()返回一個可等待對象,它會在運行時向異步生成器函數暫停的位置拋入一個 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit")。 如果該異步生成器函數正常退出、關閉或引發 [`GeneratorExit`](../library/exceptions.xhtml#GeneratorExit "GeneratorExit") (由于未捕獲該異常) 則返回的可等待對象將引發 [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration") 異常。 后續調用異步生成器所返回的任何其他可等待對象將引發 [`StopAsyncIteration`](../library/exceptions.xhtml#StopAsyncIteration "StopAsyncIteration") 異常。 如果異步生成器產生了一個值,該可等待對象會引發 [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError")。 如果異步生成器引發任何其他異常,它會被傳播給可等待對象的調用者。 如果異步生成器已經由于異常或正常退出則后續調用 [`aclose()`](#agen.aclose "agen.aclose") 將返回一個不會做任何事的可等待對象。
## 6.3. 原型
原型代表編程語言中最緊密綁定的操作。 它們的句法如下:
```
primary ::= atom | attributeref | subscription | slicing | call
```
### 6.3.1. 屬性引用
屬性引用是后面帶有一個句點加一個名稱的原型:
```
attributeref ::= primary "." identifier
```
此原型必須求值為一個支持屬性引用的類型的對象,多數對象都支持屬性引用。 隨后該對象會被要求產生以指定標識符為名稱的屬性。 這個產生過程可通過重載 [`__getattr__()`](datamodel.xhtml#object.__getattr__ "object.__getattr__") 方法來自定義。 如果這個屬性不可用,則將引發 [`AttributeError`](../library/exceptions.xhtml#AttributeError "AttributeError") 異常。 否則的話,所產生對象的類型和值會根據該對象來確定。 對同一屬性引用的多次求值可能產生不同的對象。
### 6.3.2. 抽取
抽取就是在序列(字符串、元組或列表)或映射(字典)對象中選擇一項:
```
subscription ::= primary "[" expression_list "]"
```
此原型必須求值為一個支持抽取操作的對象(例如列表或字典)。 用戶定義的對象可通過定義 [`__getitem__()`](datamodel.xhtml#object.__getitem__ "object.__getitem__") 方法來支持抽取操作。
對于內置對象,有兩種類型的對象支持抽取操作:
如果原型為映射,表達式列表必須求值為一個以該映射的鍵為值的對象,抽取操作會在映射中選出該鍵所對應的值。(表達式列表為一個元組,除非其中只有一項。)
如果原型為序列,表達式列表必須求值為一個整數或一個切片(詳情見下節)。
正式句法規則并沒有在序列中設置負標號的特殊保留條款;但是,內置序列所提供的 [`__getitem__()`](datamodel.xhtml#object.__getitem__ "object.__getitem__") 方法都可通過在索引中添加序列長度來解析負標號 (這樣 `x[-1]` 會選出 `x` 中的最后一項)。 結果值必須為一個小于序列中項數的非負整數,抽取操作會選出標號為該值的項(從零開始數)。 由于對負標號和切片的支持存在于對象的 [`__getitem__()`](datamodel.xhtml#object.__getitem__ "object.__getitem__") 方法,重載此方法的子類需要顯式地添加這種支持。
字符串的項是字符。 字符不是單獨的數據類型而是僅有一個字符的字符串。
### 6.3.3. 切片
切片就是在序列對象(字符串、元組或列表)中選擇某個范圍內的項。 切片可被用作表達式以及賦值或 [`del`](simple_stmts.xhtml#del) 語句的目標。 切片的句法如下:
```
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
```
此處的正式句法中存在一點歧義:任何形似表達式列表的東西同樣也會形似切片列表,因此任何抽取操作也可以被解析為切片。 為了不使句法更加復雜,于是通過定義將此情況解析為抽取優先于解析為切片來消除這種歧義(切片列表未包含正確的切片就屬于此情況)。
切片的語義如下所述。 元型通過一個根據下面的切片列表來構造的鍵進行索引(與普通抽取一樣使用 [`__getitem__()`](datamodel.xhtml#object.__getitem__ "object.__getitem__") 方法)。 如果切片列表包含至少一個逗號,則鍵將是一個包含切片項轉換的元組;否則的話,鍵將是單個切片項的轉換。 切片項如為一個表達式,則其轉換就是該表達式。 一個正確切片的轉換就是一個切片對象(參見 [標準類型層級結構](datamodel.xhtml#types) 一節),該對象的 `start`, `stop` 和 `step` 屬性將分別為表達式所給出的下界、上界和步長值,省略的表達式將用 `None` 來替換。
### 6.3.4. 調用
所謂調用就是附帶可能為空的一系列 [參數](../glossary.xhtml#term-argument) 來執行一個可調用對象 (例如 [function](../glossary.xhtml#term-function)):
```
call ::= primary "(" [argument_list [","] | comprehension] ")"
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
positional_arguments ::= ["*"] expression ("," ["*"] expression)*
starred_and_keywords ::= ("*" expression | keyword_item)
("," "*" expression | "," keyword_item)*
keywords_arguments ::= (keyword_item | "**" expression)
("," keyword_item | "," "**" expression)*
keyword_item ::= identifier "=" expression
```
一個可選項為在位置和關鍵字參數后加上逗號而不影響語義。
此原型必須求值為一個可調用對象(用戶定義的函數,內置函數,內置對象的方法,類對象,類實例的方法以及任何具有 [`__call__()`](datamodel.xhtml#object.__call__ "object.__call__") 方法的對象都是可調用對象)。 所有參數表達式將在嘗試調用前被求值。 請參閱 [函數定義](compound_stmts.xhtml#function) 一節了解正式的 [parameter](../glossary.xhtml#term-parameter) 列表句法。
如果存在關鍵字參數,它們會先通過以下操作被轉換為位置參數。 首先,為正式參數創建一個未填充空位的列表. 如果有 N 個位置參數,則將它們放入前 N 個空位。 然后,對于每個關鍵字參數,使用標識符來確定其對應的空位(如果標識符與第一個正式參數名相同則使用第一個個空位,依此類推)。 如果空位已被填充,則會引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") 異常。 否則,將參數值放入空位進行填充(即使表達式為 `None` 也會填充空位)。 當所有參數處理完畢時,尚未填充的空位將用來自函數定義的相應默認值來填充。 (函數一旦定義其參數默認值就會被計算;因此,當列表或字典這類可變對象被用作默認值時,將會被所有未指定相應空位參數值的調用所共享;這種情況通常應當避免。) 如果任何一個未填充空位沒有指定默認值,則會引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") 異常。 否則的話,已填充空位的列表會被作為調用的參數列表。
**CPython implementation detail:** 某些實現可能提供位置參數沒有名稱的內置函數,即使它們在文檔說明的場合下有“命名”,因此不能以關鍵字形式提供參數。 在 CPython 中,以 C 編寫并使用 [`PyArg_ParseTuple()`](../c-api/arg.xhtml#c.PyArg_ParseTuple "PyArg_ParseTuple") 來解析其參數的函數實現就屬于這種情況。
如果存在比正式參數空位多的位置參數,將會引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") 異常,除非有一個正式參數使用了 `*identifier` 句法;在此情況下,該正式參數將接受一個包含了多余位置參數的元組(如果沒有多余位置參數則為一個空元組)。
如果任何關鍵字參數沒有與之對應的正式參數名稱,將會引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") 異常,除非有一個正式參數使用了 `**identifier` 句法,該正式參數將接受一個包含了多余關鍵字參數的字典(使用關鍵字作為鍵而參數值作為與鍵對應的值),如果沒有多余關鍵字參數則為一個(新的)空字典。
如果函數調用中出現了 `*expression` 句法,`expression` 必須求值為一個 [iterable](../glossary.xhtml#term-iterable)。 來自該可迭代對象的元素會被當作是額外的位置參數。 對于 `f(x1, x2, *y, x3, x4)` 調用,如果 *y* 求值為一個序列 *y1*, ..., *yM*,則它就等價于一個帶有 M+4 個位置參數 *x1*, *x2*, *y1*, ..., *yM*, *x3*, *x4* 的調用。
這樣做的一個后果是雖然 `*expression` 句法可能出現于顯式的關鍵字參數 *之后*,但它會在關鍵字參數(以及任何 `**expression` 參數 -- 見下文) *之前* 被處理。 因此:
```
>>> def f(a, b):
... print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
```
在同一個調用中同時使用關鍵字參數和 `*expression` 句法并不常見,因此實際上這樣的混淆不會發生。
如果函數調用中出現了 `**expression` 句法,`expression` 必須求值為一個 [mapping](../glossary.xhtml#term-mapping),其內容會被當作是額外的關鍵字參數。 如果一個關鍵字已存在(作為顯式關鍵字參數,或來自另一個拆包),則將引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") 異常。
使用 `*identifier` 或 `**identifier` 句法的正式參數不能被用作位置參數空位或關鍵字參數名稱。
在 3.5 版更改: 函數調用接受任意數量的 `*` 和 `**` 拆包,位置參數可能跟在可迭代對象拆包 (`*`) 之后,而關鍵字參數可能跟在字典拆包 (`**`) 之后。 由 [**PEP 448**](https://www.python.org/dev/peps/pep-0448) \[https://www.python.org/dev/peps/pep-0448\] 發起最初提議。
除非引發了異常,調用總是會有返回值,返回值也可能為 `None`。 返回值的計算方式取決于可調用對象的類型。
如果類型為---
用戶自定義函數:函數的代碼塊會被執行,并向其傳入參數列表。 代碼塊所做的第一件事是將正式形參綁定到對應參數;相關描述參見 [函數定義](compound_stmts.xhtml#function) 一節。 當代碼塊執行 [`return`](simple_stmts.xhtml#return) 語句時,由其指定函數調用的返回值。
內置函數或方法:具體結果依賴于解釋器;有關內置函數和方法的描述參見 [內置函數](../library/functions.xhtml#built-in-funcs)。
類對象:返回該類的一個新實例。
類實例方法:調用相應的用戶自定義函數,向其傳入的參數列表會比調用的參數列表多一項:該實例將成為第一個參數。
類實例:該類必須定義有 [`__call__()`](datamodel.xhtml#object.__call__ "object.__call__") 方法;作用效果將等價于調用該方法。
## 6.4. await 表達式
掛起 [coroutine](../glossary.xhtml#term-coroutine) 的執行以等待一個 [awaitable](../glossary.xhtml#term-awaitable) 對象。 只能在 [coroutine function](../glossary.xhtml#term-coroutine-function) 內部使用。
```
await_expr ::= "await" primary
```
3\.5 新版功能.
## 6.5. 冪運算符
冪運算符的綁定比在其左側的一元運算符更緊密;但綁定緊密程度不及在其右側的一元運算符。 句法如下:
```
power ::= (await_expr | primary) ["**" u_expr]
```
因此,在一個未加圓括號的冪運算符和單目運算符序列中,運算符將從右向左求值(這不會限制操作數的求值順序): `-1**2` 結果將為 `-1`。
冪運算符與附帶兩個參數調用內置 [`pow()`](../library/functions.xhtml#pow "pow") 函數具有相同的語義:結果為對其左參數進行其右參數所指定冪次的乘方運算。 數值參數會先轉換為相同類型,結果也為轉換后的類型。
對于 int 類型的操作數,結果將具有與操作數相同的類型,除非第二個參數為負數;在那種情況下,所有參數會被轉換為 float 類型并輸出 float 類型的結果。 例如,`10**2` 返回 `100`,而 `10**-2` 返回 `0.01`。
對 `0.0` 進行負數冪次運算將導致 [`ZeroDivisionError`](../library/exceptions.xhtml#ZeroDivisionError "ZeroDivisionError")。 對負數進行分數冪次運算將返回 [`complex`](../library/functions.xhtml#complex "complex") 數值。 (在早期版本中這將引發 [`ValueError`](../library/exceptions.xhtml#ValueError "ValueError")。)
## 6.6. 一元算術和位運算
所有算術和位運算具有相同的優先級:
```
u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr
```
一元運算符 `-` (負) 會產生其數值參數的負值。
一元運算符 `+` (正) 會產生與其數值參數相同的值。
一元運算符 `~` (取反) 的結果是對其整數參數按位取反。 `x` 的按位取反被定義為 `-(x+1)`。 它只作用于整數。
在所有三種情況下,如果參數的類型不正確,將引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") 異常。
## 6.7. 二元算術運算符
二元算術運算符遵循傳統的優先級。 請注意某些此類運算符也作用于特定的非數字類型。 除冪運算符以外只有兩個優先級別,一個作用于乘法型運算符,另一個作用于加法型運算符:
```
m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_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
```
運算符 `*` (乘) 將輸出其參數的乘積。 兩個參數或者必須都為數字,或者一個參數必須為整數而另一個參數必須為序列。 在前一種情況下,兩個數字將被轉換為相同類型然后相乘。 在后一種情況下,將執行序列的重復;重復因子為負數將輸出空序列。
運算符 `@` (at) 的目標是用于矩陣乘法。 沒有內置 Python 類型實現此運算符。
3\.5 新版功能.
運算符 `/` (除) 和 `//` (整除) 將輸出其參數的商。 兩個數字參數將先被轉換為相同類型。 整數相除會輸出一個 float 值,整數相整除的結果仍是整數;整除的結果就是使用 'floor' 函數進行算術除法的結果。 除以零的運算將引發 [`ZeroDivisionError`](../library/exceptions.xhtml#ZeroDivisionError "ZeroDivisionError") 異常。
運算符 `%` (模) 將輸出第一個參數除以第二個參數的余數。 兩個數字參數將先被轉換為相同類型。 右參數為零將引發 [`ZeroDivisionError`](../library/exceptions.xhtml#ZeroDivisionError "ZeroDivisionError") 異常。 參數可以為浮點數,例如 `3.14%0.7` 等于 `0.34` (因為 `3.14` 等于 `4*0.7 + 0.34`)。 模運算符的結果的正負總是與第二個操作數一致(或是為零);結果的絕對值一定小于第二個操作數的絕對值 [1](#id17)。
整除與模運算符的聯系可通過以下等式說明: `x == (x//y)*y + (x%y)`。 此外整除與模也可通過內置函數 [`divmod()`](../library/functions.xhtml#divmod "divmod") 來同時進行: `divmod(x, y) == (x//y, x%y)`。 [2](#id18)。
除了對數字執行模運算,運算符 `%` 還被字符串對象重載用于執行舊式的字符串格式化(又稱插值)。 字符串格式化句法的描述參見 Python 庫參考的 [printf 風格的字符串格式化](../library/stdtypes.xhtml#old-string-formatting) 一節。
整除運算符,模運算符和 [`divmod()`](../library/functions.xhtml#divmod "divmod") 函數未被定義用于復數。 如果有必要可以使用 [`abs()`](../library/functions.xhtml#abs "abs") 函數將其轉換為浮點數。
運算符 `+` (addition) 將輸出其參數的和。 兩個參數或者必須都為數字,或者都為相同類型的序列。 在前一種情況下,兩個數字將被轉換為相同類型然后相加。 在后一種情況下,將執行序列拼接操作。
運算符 `-` (減) 將輸出其參數的差。 兩個數字參數將先被轉換為相同類型。
## 6.8. 移位運算
移位運算的優先級低于算術運算:
```
shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr
```
這些運算符接受整數參數。 它們會將第一個參數左移或右移第二個參數所指定的比特位數。
右移 *n* 位被定義為被 `pow(2,n)` 整除。 左移 *n* 位被定義為乘以 `pow(2,n)`。
## 6.9. 二元位運算
三種位運算具有各不相同的優先級:
```
and_expr ::= shift_expr | and_expr "&" shift_expr
xor_expr ::= and_expr | xor_expr "^" and_expr
or_expr ::= xor_expr | or_expr "|" xor_expr
```
運算符 `&` 對兩個參數進行按位 AND (與) 運算,兩個參數必須為整數。
運算符 `^` 對兩個參數進行按位 XOR (異或) 運算,兩個參數必須為整數。
運算符 `|` 對兩個參數進行按位 OR (或) 運算,兩個參數必須為整數。
## 6.10. 比較運算
與 C 不同,Python 中所有比較運算的優先級相同,低于任何算術、移位或位運算。 另一個與 C 不同之處在于 `a < b < c` 這樣的表達式會按傳統算術法則來解讀:
```
comparison ::= or_expr (comp_operator or_expr)*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
```
比較運算將輸出布爾值: `True` 或 `False`。
比較運算可以任意串連,例如 `x < y <= z` 等價于 `x < y and y <= z`,除了 `y` 只被求值一次(但在兩種寫法下當 `x < y` 值為假時 `z` 都不會被求值)。
正式的說法是這樣:如果 *a*, *b*, *c*, ..., *y*, *z* 為表達式而 *op1*, *op2*, ..., *opN* 為比較運算符,則 `a op1 b op2 c ... y opN z` 就等價于 `a op1 b and b op2 c and ... y opN z`,后者的不同之處只是每個表達式最多只被求值一次。
請注意 `a op1 b op2 c` 不意味著在 *a* 和 *c* 之間進行任何比較,因此,如 `x < y > z` 這樣的寫法是完全合法的(雖然也許不太好看)。
### 6.10.1. 值比較
運算符 `<`, `>`, `==`, `>=`, `<=` 和 `!=` 將比較兩個對象的值。 兩個對象不要求為相同類型。
[對象、值與類型](datamodel.xhtml#objects) 一章已說明對象都有相應的值(還有類型和標識號)。 對象值在 Python 中是一個相當抽象的概念:例如,對象值并沒有一個規范的訪問方法。 而且,對象值并不要求具有特定的構建方式,例如由其全部數據屬性組成等。 比較運算符實現了一個特定的對象值概念。 人們可以認為這是通過實現對象比較間接地定義了對象值。
由于所有類型都是 [`object`](../library/functions.xhtml#object "object") 的(直接或間接)子類型,它們都從 [`object`](../library/functions.xhtml#object "object") 繼承了默認的比較行為。 類型可以通過實現 *豐富比較方法* 例如 [`__lt__()`](datamodel.xhtml#object.__lt__ "object.__lt__") 來定義自己的比較行為,詳情參見 [基本定制](datamodel.xhtml#customization)。
默認的一致性比較 (`==` 和 `!=`) 是基于對象的標識號。 因此,具有相同標識號的實例一致性比較結果為相等,具有不同標識號的實例一致性比較結果為不等。 規定這種默認行為的動機是希望所有對象都應該是自反射的 (即 `x is y` 就意味著 `x == y`)。
次序比較 (`<`, `>`, `<=` 和 `>=`) 默認沒有提供;如果嘗試比較會引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError")。 規定這種默認行為的原因是缺少與一致性比較類似的固定值。
按照默認的一致性比較行為,具有不同標識號的實例總是不相等,這可能不適合某些對象值需要有合理定義并有基于值的一致性的類型。 這樣的類型需要定制自己的比較行為,實際上,許多內置類型都是這樣做的。
以下列表描述了最主要內置類型的比較行為。
- 內置數值類型 ([數字類型 --- int, float, complex](../library/stdtypes.xhtml#typesnumeric)) 以及標準庫類型 [`fractions.Fraction`](../library/fractions.xhtml#fractions.Fraction "fractions.Fraction") 和 [`decimal.Decimal`](../library/decimal.xhtml#decimal.Decimal "decimal.Decimal") 可進行類型內部和跨類型的比較,例外限制是復數不支持次序比較。 在類型相關的限制以內,它們會按數學(算法)規則正確進行比較且不會有精度損失。
非數字值 `float('NaN')` 和 `decimal.Decimal('NaN')` 屬于特例。 任何數字與非數字值的比較均返回假值。 還有一個反直覺的結果是非數字值不等于其自身。 例如,如果 `x = float('NaN')` 則 `3 < x`, `x < 3`, `x == x`, `x != x` 均為假值。 此行為是符合 IEEE 754 標準的。
- 二進制碼序列 ([`bytes`](../library/stdtypes.xhtml#bytes "bytes") 或 [`bytearray`](../library/stdtypes.xhtml#bytearray "bytearray") 的實例) 可進行類型內部和跨類型的比較。 它們使用其元素的數字值按字典順序進行比較。
- 字符串 ([`str`](../library/stdtypes.xhtml#str "str") 的實例) 使用其字符的 Unicode 碼位數字值 (內置函數 [`ord()`](../library/functions.xhtml#ord "ord") 的結果) 按字典順序進行比較。 [3](#id19)
字符串和二進制碼序列不能直接比較。
- 序列 ([`tuple`](../library/stdtypes.xhtml#tuple "tuple"), [`list`](../library/stdtypes.xhtml#list "list") 或 [`range`](../library/stdtypes.xhtml#range "range") 的實例) 只可進行類型內部的比較,range 還有一個限制是不支持次序比較。 以上對象的跨類型一致性比較結果將是不相等,跨類型次序比較將引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError")。
序列通過相應元素的比較進行字典列比較,并強制規定元素自反射性。
由于強制元素自反射性,多項集的比較將假定對于一個多項集元素 `x`, `x == x` 總是為真。 基于該假設,將首先比較元素標識號,并且僅會對不同元素執行元素比較。 如果元素是自反射的,這種方式會產生與嚴格元素比較相同的結果。 對于非自反射的元素,結果將不同于嚴格元素比較,并且可能會令人驚訝:例如當在列表中使用非自反射的非數字值時,將導致以下比較行為:
```
>>> nan = float('NaN')
>>> nan is nan
True
>>> nan == nan
False <-- the defined non-reflexive behavior of NaN
>>> [nan] == [nan]
True <-- list enforces reflexivity and tests identity first
```
內置多項集間的字典序比較規則如下:
- 兩個多項集若要相等,它們必須為相同類型、相同長度,并且每對相應的元素都必須相等(例如,`[1,2] == (1,2)` 為假值,因為類型不同)。
- 對于支持次序比較的多項集,排序與其第一個不相等元素的排序相同(例如 `[1,2,x] <= [1,2,y]` 的值與``x <= y`` 相同)。 如果對應元素不存在,較短的多項集排序在前(例如 `[1,2] < [1,2,3]` 為真值)。
- 兩個映射 ([`dict`](../library/stdtypes.xhtml#dict "dict") 的實例) 若要相等,必須當且僅當它們具有相同的 (鍵, 值) 對。 鍵和值的一致性比較強制規定自反射性。
次序比較 (`<`, `>`, `<=` 和 `>=`) 將引發 [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError")。
- 集合 ([`set`](../library/stdtypes.xhtml#set "set") 或 [`frozenset`](../library/stdtypes.xhtml#frozenset "frozenset") 的實例) 可進行類型內部和跨類型的比較。
它們將比較運算符定義為子集和超集檢測。 這類關系沒有定義完全排序(例如 `{1,2}` 和 `{2,3}` 兩個集合不相等,即不為彼此的子集,也不為彼此的超集。 相應地,集合不適宜作為依賴于完全排序的函數的參數(例如如果給出一個集合列表作為 [`min()`](../library/functions.xhtml#min "min"), [`max()`](../library/functions.xhtml#max "max") 和 [`sorted()`](../library/functions.xhtml#sorted "sorted") 的輸入將產生未定義的結果)。
集合的比較強制規定其元素的自反射性。
- 大多數其他內置類型沒有實現比較方法,因此它們會繼承默認的比較行為。
在可能的情況下,用戶定義類在定制其比較行為時應當遵循一些一致性規則:
- 相等比較應該是自反射的。 換句話說,相同的對象比較時應該相等:
> `x is y` 意味著 `x == y`
- 比較應該是對稱的。 換句話說,下列表達式應該有相同的結果:
> `x == y` 和 `y == x`
>
> `x != y` 和 `y != x`
>
> `x < y` 和 `y > x`
>
> `x <= y` 和 `y >= x`
- 比較應該是可傳遞的。 下列(簡要的)例子顯示了這一點:
> `x > y and y > z` 意味著 `x > z`
>
> `x < y and y <= z` 意味著 `x < z`
- 反向比較應該導致布爾值取反。 換句話說,下列表達式應該有相同的結果:
> `x == y` 和 `not x != y`
>
> `x < y` 和 `not x >= y` (對于完全排序)
>
> `x > y` 和 `not x <= y` (對于完全排序)
最后兩個表達式適用于完全排序的多項集(即序列而非集合或映射)。 另請參閱 [`total_ordering()`](../library/functools.xhtml#functools.total_ordering "functools.total_ordering") 裝飾器。
- [`hash()`](../library/functions.xhtml#hash "hash") 的結果應該與是否相等一致。 相等的對象應該或者具有相同的哈希值,或者標記為不可哈希。
Python 并不強制要求這些一致性規則。 實際上,非數字值就是一個不遵循這些規則的例子。
### 6.10.2. 成員檢測運算
運算符 [`in`](#in) 和 [`not in`](#not-in) 用于成員檢測。 如果 *x* 是 *s* 的成員則 `x in s` 求值為 `True`,否則為 `False`。 `x not in s` 返回 `x in s` 取反后的值。 所有內置序列和集合類型以及字典都支持此運算,對于字典來說 `in` 檢測其是否有給定的鍵。 對于 list, tuple, set, frozenset, dict 或 collections.deque 這樣的容器類型,表達式 `x in y` 等價于 `any(x is e or x == e for e in y)`。
對于字符串和字節串類型來說,當且僅當 *x* 是 *y* 的子串時 `x in y` 為 `True`。 一個等價的檢測是 `y.find(x) != -1`。 空字符串總是被視為任何其他字符串的子串,因此 `"" in "abc"` 將返回 `True`。
對于定義了 [`__contains__()`](datamodel.xhtml#object.__contains__ "object.__contains__") 方法的用戶自定義類來說,如果 `y.__contains__(x)` 返回真值則 `x in y` 返回 `True`,否則返回 `False`。
對于未定義 [`__contains__()`](datamodel.xhtml#object.__contains__ "object.__contains__") 但定義了 [`__iter__()`](datamodel.xhtml#object.__iter__ "object.__iter__") 的用戶自定義類來說,如果在對 `y` 進行迭代時產生了值 `z` 且 `x == z` 則 `x in y` 為 `True`。 如果在迭代期間引發了異常,則等同于 [`in`](#in) 引發了該異常。
最后會嘗試舊式的迭代協議:如果一個類定義了 [`__getitem__()`](datamodel.xhtml#object.__getitem__ "object.__getitem__"),則當且僅當存在非負整數索引 *i* 使得 `x == y[i]` 并且所有更小索引未引發 [`IndexError`](../library/exceptions.xhtml#IndexError "IndexError") 異常時 `x in y` 為 `True`。 (如果引發了任何其他異常,則等同于 [`in`](#in) 引發了該異常)。
The operator [`not in`](#not-in) is defined to have the inverse truth value of [`in`](#in).
### 6.10.3. 標識號比較
The operators [`is`](#is) and [`is not`](#is-not) test for an object's identity:
```
x
is y
```
is true if and only if *x* and *y* are the same object. An Object's identity is determined using the [`id()`](../library/functions.xhtml#id "id") function. `x is not y` yields the inverse truth value. [4](#id20)
## 6.11. 布爾運算
```
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
```
在執行布爾運算的情況下,或是當表達式被用于流程控制語句時,以下值會被解析為假值: `False`, `None`, 所有類型的數字零,以及空字符串和空容器(包括字符串、元組、列表、字典、集合與凍結集合)。 所有其他值都會被解析為真值。 用戶自定義對象可通過提供 [`__bool__()`](datamodel.xhtml#object.__bool__ "object.__bool__") 方法來定制其邏輯值。
運算符 [`not`](#not) 將在其參數為假值時產生 `True`,否則產生 `False`。
表達式 `x and y` 首先對 *x* 求值;如果 *x* 為假則返回該值;否則對 *y* 求值并返回其結果值。
表達式 `x or y` 首先對 *x* 求值;如果 *x* 為真則返回該值;否則對 *y* 求值并返回其結果值。
請注意 [`and`](#and) 和 [`or`](#or) 都不限制其返回的值和類型必須為 `False` 和 `True`,而是返回最終求值的參數。 此行為是有必要的,例如假設 `s` 為一個當其為空時應被替換為某個默認值的字符串,表達式 `s or 'foo'` 將產生希望的值。 由于 [`not`](#not) 必須創建一個新值,不論其參數為何種類型它都會返回一個布爾值(例如,`not 'foo'` 結果為 `False` 而非 `''`。)
## 6.12. 條件表達式
```
conditional_expression ::= or_test ["if" or_test "else" expression]
expression ::= conditional_expression | lambda_expr
expression_nocond ::= or_test | lambda_expr_nocond
```
條件表達式(有時稱為“三元運算符”)在所有 Python 運算中具有最低的優先級。
表達式 `x if C else y` 首先是對條件 *C* 而非 *x* 求值。 如果 *C* 為真,*x* 將被求值并返回其值;否則將對 *y* 求值并返回其值。
請參閱 [**PEP 308**](https://www.python.org/dev/peps/pep-0308) \[https://www.python.org/dev/peps/pep-0308\] 了解有關條件表達式的詳情。
## 6.13. lambda 表達式
```
lambda_expr ::= "lambda" [parameter_list] ":" expression
lambda_expr_nocond ::= "lambda" [parameter_list] ":" expression_nocond
```
lambda 表達式(有時稱為 lambda 構型)被用于創建匿名函數。 表達式 `lambda parameters: expression` 會產生一個函數對象 。 該未命名對象的行為類似于用以下方式定義的函數:
```
def <lambda>(parameters):
return expression
```
請參閱 [函數定義](compound_stmts.xhtml#function) 了解有關參數列表的句法。 請注意通過 lambda 表達式創建的函數不能包含語句或標注。
## 6.14. 表達式列表
```
expression_list ::= expression ("," expression)* [","]
starred_list ::= starred_item ("," starred_item)* [","]
starred_expression ::= expression | (starred_item ",")* [starred_item]
starred_item ::= expression | "*" or_expr
```
除了作為列表或集合顯示的一部分,包含至少一個逗號的表達式列表將生成一個元組。 元組的長度就是列表中表達式的數量。 表達式將從左至右被求值。
一個星號 `*` 表示 *可迭代拆包*。 其操作數必須為一個 [iterable](../glossary.xhtml#term-iterable)。 該可迭代對象將被拆解為迭代項的序列,并被包含于在拆包位置上新建的元組、列表或集合之中。
3\.5 新版功能: 表達式列表中的可迭代對象拆包,最初由 [**PEP 448**](https://www.python.org/dev/peps/pep-0448) \[https://www.python.org/dev/peps/pep-0448\] 提出。
末尾的逗號僅在創建單獨元組 (或稱 *單例*) 時需要;在所有其他情況下都是可選項。 沒有末尾逗號的單獨表達式不會創建一個元組,而是產生該表達式的值。 (要創建一個空元組,應使用一對內容為空的圓括號: `()`。)
## 6.15. 求值順序
Python 按從左至右的順序對表達式求值。 但注意在對賦值操作求值時,右側會先于左側被求值。
在以下幾行中,表達式將按其后綴的算術優先順序被求值。:
```
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
```
## 6.16. 運算符優先級
下表對 Python 中運算符的優先順序進行了總結,從最低優先級(最后綁定)到最高優先級(最先綁定)。 相同單元格內的運算符具有相同優先級。 除非句法顯式地給出,否則運算符均指二元運算。 相同單元格內的運算符均從左至右分組(除了冪運算是從右至左分組)。
請注意比較、成員檢測和標識號檢測均為相同優先級,并具有如 [比較運算](#comparisons) 一節所描述的從左至右串連特性。
運算符
描述
[`lambda`](#lambda)
lambda 表達式
[`if`](#if-expr) -- `else`
條件表達式
[`or`](#or)
布爾邏輯或 OR
[`and`](#and)
布爾邏輯與 AND
[`not`](#not)`x`
布爾邏輯非 NOT
[`in`](#in), [`not in`](#not-in), [`is`](#is), [`is not`](#is-not), `<`, `<=`, `>`, `>=`, `!=`, `==`
比較運算,包括成員檢測和標識號檢測
`|`
按位或 OR
`^`
按位異或 XOR
`&`
按位與 AND
`<<`, `>>`
移位
`+`, `-`
加和減
`*`, `@`, `/`, `//`, `%`
乘,矩陣乘,除,整除,取余 [5](#id21)
`+x`, `-x`, `~x`
正,負,按位非 NOT
`**`
乘方 [6](#id22)
[`await`](#await)`x`
await 表達式
`x[index]`, `x[index:index]`, `x(arguments...)`, `x.attribute`
抽取,切片,調用,屬性引用
`(expressions...)`, `[expressions...]`, `{key: value...}`, `{expressions...}`
綁定或元組顯示,列表顯示,字典顯示,集合顯示
腳注
[1](#id9)雖然 `abs(x%y) < abs(y)` 在數學中必為真,但對于浮點數而言,由于舍入的存在,其在數值上未必為真。 例如,假設在某個平臺上的 Python 浮點數為一個 IEEE 754 雙精度數值,為了使 `-1e-100 % 1e100` 具有與 `1e100` 相同的正負性,計算結果將是 `-1e-100 + 1e100`,這在數值上正好等于 `1e100`。 函數 [`math.fmod()`](../library/math.xhtml#math.fmod "math.fmod") 返回的結果則會具有與第一個參數相同的正負性,因此在這種情況下將返回 `-1e-100`。 何種方式更適宜取決于具體的應用。
[2](#id10)如果 x 恰好非常接近于 y 的整數倍,則由于舍入的存在 `x//y` 可能會比 `(x-x%y)//y` 大。 在這種情況下,Python 會返回后一個結果,以便保持令 `divmod(x,y)[0] * y + x % y` 盡量接近 `x`.
[3](#id12)Unicode 標準明確區分 *碼位* (例如 U+0041) 和 *抽象字符* (例如 "大寫拉丁字母 A")。 雖然 Unicode 中的大多數抽象字符都只用一個碼位來代表,但也存在一些抽象字符可使用由多個碼位組成的序列來表示。 例如,抽象字符 "帶有下加符的大寫拉丁字母 C" 可以用 U+00C7 碼位上的單個 *預設字符* 來表示,也可以用一個 U+0043 碼位上的 *基礎字符* (大寫拉丁字母 C) 加上一個 U+0327 碼位上的 *組合字符* (組合下加符) 組成的序列來表示。
對于字符串,比較運算符會按 Unicode 碼位級別進行比較。 這可能會違反人類的直覺。 例如,`"\u00C7" == "\u0043\u0327"` 為 `False`,雖然兩個字符串都代表同一個抽象字符 "帶有下加符的大寫拉丁字母 C"。
要按抽象字符級別(即對人類來說更直觀的方式)對字符串進行比較,應使用 [`unicodedata.normalize()`](../library/unicodedata.xhtml#unicodedata.normalize "unicodedata.normalize")。
[4](#id13)由于存在自動垃圾收集、空閑列表以及描述器的動態特性,你可能會注意到在特定情況下使用 [`is`](#is) 運算符會出現看似不正常的行為,例如涉及到實例方法或常量之間的比較時就是如此。 更多信息請查看有關它們的文檔。
[5](#id15)`%` 運算符也被用于字符串格式化;在此場合下會使用同樣的優先級。
[6](#id16)冪運算符 `**` 綁定的緊密程度低于在其右側的算術或按位一元運算符,也就是說 `2**-1` 為 `0.5`。
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](simple_stmts.xhtml "7. 簡單語句") |
- [上一頁](import.xhtml "5. 導入系統") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 語言參考](index.xhtml) ?
- $('.inline-search').show(0); |
? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec