### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](design.xhtml "設計和歷史常見問題") |
- [上一頁](general.xhtml "Python常見問題") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 常見問題](index.xhtml) ?
- $('.inline-search').show(0); |
# [編程常見問題](#id2)
目錄
- [編程常見問題](#programming-faq)
- [一般問題](#general-questions)
- [Python 有沒有提供斷點與單步調試等功能的,源碼層次的調試器?](#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc)
- [有沒有工具來幫助找尋漏洞或進行靜態分析?](#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis)
- [我如何能夠通過一個 Python 腳本創建一個獨立運行的二進制文件?](#how-can-i-create-a-stand-alone-binary-from-a-python-script)
- [是否有編程標準或Python程序的樣式指南?](#are-there-coding-standards-or-a-style-guide-for-python-programs)
- [核心語言](#core-language)
- [當變量有值時,為什么會出現UnboundLocalError?](#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value)
- [Python中的局部變量和全局變量有哪些規則?](#what-are-the-rules-for-local-and-global-variables-in-python)
- [為什么在具有不同值的循環中定義的lambdas都返回相同的結果?](#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result)
- [如何跨模塊共享全局變量?](#how-do-i-share-global-variables-across-modules)
- [導入模塊的“最佳實踐”是什么?](#what-are-the-best-practices-for-using-import-in-a-module)
- [為什么對象之間共享默認值?](#why-are-default-values-shared-between-objects)
- [如何將可選參數或關鍵字參數從一個函數傳遞到另一個函數?](#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another)
- [形參和實參之間有什么區別?](#what-is-the-difference-between-arguments-and-parameters)
- [為什么更改列表'y'也會更改列表'x'?](#why-did-changing-list-y-also-change-list-x)
- [如何編寫帶輸出參數的函數(通過引用調用)?](#how-do-i-write-a-function-with-output-parameters-call-by-reference)
- [如何在Python中創建高階函數?](#how-do-you-make-a-higher-order-function-in-python)
- [如何在Python中復制對象?](#how-do-i-copy-an-object-in-python)
- [如何找到對象的方法或屬性?](#how-can-i-find-the-methods-or-attributes-of-an-object)
- [我的代碼如何才能發現對象的名稱?](#how-can-my-code-discover-the-name-of-an-object)
- [逗號運算符的優先級是什么?](#what-s-up-with-the-comma-operator-s-precedence)
- [Is there an equivalent of C's "?:" ternary operator?](#is-there-an-equivalent-of-c-s-ternary-operator)
- [Is it possible to write obfuscated one-liners in Python?](#is-it-possible-to-write-obfuscated-one-liners-in-python)
- [函數參數列表中的斜杠(/)是什么意思?](#what-does-the-slash-in-the-parameter-list-of-a-function-mean)
- [數字和字符串](#numbers-and-strings)
- [如何指定十六進制和八進制整數?](#how-do-i-specify-hexadecimal-and-octal-integers)
- [為什么-22 // 10返回-3?](#why-does-22-10-return-3)
- [如何將字符串轉換為數字?](#how-do-i-convert-a-string-to-a-number)
- [如何將數字轉換為字符串?](#how-do-i-convert-a-number-to-a-string)
- [如何修改字符串?](#how-do-i-modify-a-string-in-place)
- [如何使用字符串調用函數/方法?](#how-do-i-use-strings-to-call-functions-methods)
- [Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?](#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings)
- [Is there a scanf() or sscanf() equivalent?](#is-there-a-scanf-or-sscanf-equivalent)
- [What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?](#what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean)
- [性能](#performance)
- [我的程序太慢了。該如何加快速度?](#my-program-is-too-slow-how-do-i-speed-it-up)
- [將多個字符串連接在一起的最有效方法是什么?](#what-is-the-most-efficient-way-to-concatenate-many-strings-together)
- [序列(元組/列表)](#sequences-tuples-lists)
- [如何在元組和列表之間進行轉換?](#how-do-i-convert-between-tuples-and-lists)
- [什么是負數序號?](#what-s-a-negative-index)
- [如何以相反的順序迭代序列?](#how-do-i-iterate-over-a-sequence-in-reverse-order)
- [如何從列表中刪除重復項?](#how-do-you-remove-duplicates-from-a-list)
- [你如何在Python中創建一個數組?](#how-do-you-make-an-array-in-python)
- [如何創建多維列表?](#how-do-i-create-a-multidimensional-list)
- [如何將方法應用于一系列對象?](#how-do-i-apply-a-method-to-a-sequence-of-objects)
- [Why does a\_tuple\[i\] += \['item'\] raise an exception when the addition works?](#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works)
- [I want to do a complicated sort: can you do a Schwartzian Transform in Python?](#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python)
- [如何按其他列表中的值對一個列表進行排序?](#how-can-i-sort-one-list-by-values-from-another-list)
- [對象](#objects)
- [什么是類?](#what-is-a-class)
- [What is a method?](#what-is-a-method)
- [什么是self?](#what-is-self)
- [如何檢查對象是否是給定類或其子類的實例?](#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it)
- [什么是代理?](#what-is-delegation)
- [如何從覆蓋基類的派生類調用基類中定義的方法?](#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it)
- [如何組織代碼以便更改基類?](#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class)
- [如何創建靜態類數據和靜態類方法?](#how-do-i-create-static-class-data-and-static-class-methods)
- [如何在Python中重載構造函數(或方法)?](#how-can-i-overload-constructors-or-methods-in-python)
- [I try to use \_\_spam and I get an error about \_SomeClassName\_\_spam.](#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam)
- [My class defines \_\_del\_\_ but it is not called when I delete the object.](#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object)
- [如何獲取給定類的所有實例的列表?](#how-do-i-get-a-list-of-all-instances-of-a-given-class)
- [為什么 `id()` 的結果看起來不是唯一的?](#why-does-the-result-of-id-appear-to-be-not-unique)
- [模塊](#modules)
- [怎么創建.pyc文件?](#how-do-i-create-a-pyc-file)
- [如何找到當前模塊名稱?](#how-do-i-find-the-current-module-name)
- [怎樣才能擁有相互導入的模塊?](#how-can-i-have-modules-that-mutually-import-each-other)
- [\_\_import\_\_('x.y.z') returns <module 'x'>; 如何獲取z?](#import-x-y-z-returns-module-x-how-do-i-get-z)
- [當我編輯導入的模塊并重新導入它時,更改不會顯示。為什么會這樣?](#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen)
## [一般問題](#id3)
### [Python 有沒有提供斷點與單步調試等功能的,源碼層次的調試器?](#id4)
有的。
Several debuggers for Python are described below, and the built-in function [`breakpoint()`](../library/functions.xhtml#breakpoint "breakpoint") allows you to drop into any of them.
pdb 模塊是一個簡單但是夠用的控制臺模式 Python 調試器。 它是標準 Python 庫的一部分,并且 [`已收錄于庫參考手冊`](../library/pdb.xhtml#module-pdb "pdb: The Python debugger for interactive interpreters.")。 你也可以通過使用 pdb 代碼作為樣例來編寫你自己的調試器。
作為標準 Python 發行版附帶組件的 IDLE 交互式環境(通常位于 Tools/scripts/idle)中包含一個圖形化的調試器。
PythonWin 是一個包含有基于 pdb 的 GUI 調試器的 Python IDE。 Pythonwin 調試器會為斷點加上顏色,并具有許多很棒的特性,例如也可以非 Pythonwin 程序。 Pythonwin 是 [Python for Windows Extensions](https://sourceforge.net/projects/pywin32/) \[https://sourceforge.net/projects/pywin32/\] 項目的一部分,也是 ActivePython 發行版的一部分(參見 <https://www.activestate.com/activepython>)。
[Boa Constructor](http://boa-constructor.sourceforge.net/) \[http://boa-constructor.sourceforge.net/\] 是一個使用wxWidgets的IDE和GUI構建器。它提供可視化框架創建和操作,對象檢查器,源對象瀏覽器上的許多視圖,繼承層次結構,doc字符串生成的html文檔,高級調試器,集成幫助和Zope支持。
[Eric](http://eric-ide.python-projects.org/) \[http://eric-ide.python-projects.org/\] 是一個基于PyQt和Scintilla編輯組件構建的IDE。
Pydb是標準Python調試器pdb的一個版本,經過修改后可與DDD(數據顯示調試器)一起使用,DDD是一種流行的圖形化調試器前端。 Pydb可以在 <http://bashdb.sourceforge.net/pydb/> 找到,DDD可以在 <https://www.gnu.org/software/ddd> 找到。
有許多商業Python IDE包括圖形調試器。他們包括:
- Wing IDE (<https://wingware.com/>)
- Komodo IDE (<https://komodoide.com/>)
- PyCharm (<https://www.jetbrains.com/pycharm/>)
### [有沒有工具來幫助找尋漏洞或進行靜態分析?](#id5)
有的。
PyChecker 是一個尋找Python代碼漏洞以及對代碼復雜性和風格給出警告的工具。你可以從這里獲得PyChecker: <http://pychecker.sourceforge.net/> 。
[Pylint](https://www.pylint.org/) \[https://www.pylint.org/\] 是另一個檢查模塊是否滿足編碼標準的工具,也可以編寫插件來添加自定義功能。除了PyChecker 執行的錯誤檢查之外, Pylint 還提供了一些額外的功能,例如檢查行長度,變量名稱是否根據您的編碼標準格式良好,聲明的接口是否完全實現等等。 <https://docs.pylint.org/> 提供了Pylint功能的完整列表。
靜態類型檢查器,例如 [Mypy](http://mypy-lang.org/) \[http://mypy-lang.org/\] 、 [Pyre](https://pyre-check.org/) \[https://pyre-check.org/\] 和 [Pytype](https://github.com/google/pytype) \[https://github.com/google/pytype\] 可以檢查Python源代碼中的類型提示。
### [我如何能夠通過一個 Python 腳本創建一個獨立運行的二進制文件?](#id6)
如果你想要的只是一個獨立的程序,用戶可以下載和運行而不必先安裝Python發行版,你就不需要將Python編譯成C代碼。有許多工具可以確定程序所需的模塊集,并將這些模塊與Python二進制文件綁定在一起以生成單個可執行文件。
一種是使用凍結工具,它包含在Python源代碼樹 `Tools/freeze` 中。它將Python字節代碼轉換為C數組;一個C編譯器,你可以將所有模塊嵌入到一個新程序中,然后將其與標準Python模塊鏈接。
它的工作原理是遞歸掃描源代碼以獲取import語句(兩種形式),并在標準Python路徑和源目錄(用于內置模塊)中查找模塊。 然后,它將用Python編寫的模塊的字節碼轉換為C代碼(可以使用編組模塊轉換為代碼對象的數組初始化器),并創建一個定制的配置文件,該文件僅包含程序中實際使用的內置模塊。 然后,它編譯生成的C代碼并將其與Python解釋器的其余部分鏈接,以形成一個獨立的二進制文件,其行為與你的腳本完全相同。
顯然, freeze 需要一個C編譯器。有幾個其他實用工具不需要。 一個是Thomas Heller的py2exe(僅限Windows)
> <http://www.py2exe.org/>
另一個工具是 Anthony Tuininga 的 [cx\_Freeze](https://anthony-tuininga.github.io/cx_Freeze/) \[https://anthony-tuininga.github.io/cx\_Freeze/\]。
### [是否有編程標準或Python程序的樣式指南?](#id7)
是。標準庫模塊所要求的編碼樣式文檔為 [**PEP 8**](https://www.python.org/dev/peps/pep-0008) \[https://www.python.org/dev/peps/pep-0008\] 。
## [核心語言](#id8)
### [當變量有值時,為什么會出現UnboundLocalError?](#id9)
通過在函數體中的某處添加賦值語句,導致以前正常工作的代碼被修改而得到 UnboundLocalError 會令人感到意外。
以下代碼:
```
>>> x = 10
>>> def bar():
... print(x)
>>> bar()
10
```
正常工作,但是以下代碼
```
>>> x = 10
>>> def foo():
... print(x)
... x += 1
```
會得到一個 UnboundLocalError :
```
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment
```
這是因為當你對作用域中的變量進行賦值時,該變量將成為該作用域的局部變量,并在外部作用域中隱藏任何類似命名的變量。由于foo中的最后一個語句為 `x` 分配了一個新值,編譯器會將其識別為局部變量。因此,當先前的 `print(x)` 嘗試打印未初始化的局部變量時會導致錯誤。
在上面的示例中,你可以通過將其聲明為全局來訪問外部作用域變量:
```
>>> x = 10
>>> def foobar():
... global x
... print(x)
... x += 1
>>> foobar()
10
```
這個顯式聲明是必需的,以便提醒你(與類和實例變量的表面類似情況不同),你實際上是在外部作用域中修改變量的值
```
>>> print(x)
11
```
你可以使用 [`nonlocal`](../reference/simple_stmts.xhtml#nonlocal) 關鍵字在嵌套作用域中執行類似的操作:
```
>>> def foo():
... x = 10
... def bar():
... nonlocal x
... print(x)
... x += 1
... bar()
... print(x)
>>> foo()
10
11
```
### [Python中的局部變量和全局變量有哪些規則?](#id10)
在Python中,僅在函數內引用的變量是隱式全局變量。如果在函數體內的任何位置為變量賦值,則除非明確聲明為全局,否則將其視為局部值。
雖然起初有點令人驚訝,但片刻考慮就可以解釋。一方面,要求 [`global`](../reference/simple_stmts.xhtml#global) 表示已分配的變量可以防止意外的副作用。另一方面,如果所有全局引用都需要 `global` ,那么你一直都在使用 `global` 。你必須將對內置函數或導入模塊的組件的每個引用聲明為全局。這種雜亂會破壞 `global` 聲明用于識別副作用的有用性。
### [為什么在具有不同值的循環中定義的lambdas都返回相同的結果?](#id11)
假設你使用for循環來定義幾個不同的 lambda (甚至是普通函數),例如::
```
>>> squares = []
>>> for x in range(5):
... squares.append(lambda: x**2)
```
這給你一個包含5個lambdas的列表,它們計算 `x**2` 。你可能會期望,當它們被調用時,它們將分別返回 `0` 、 `1` 、 `4` 、 `9` 和 `16` 。但是,當你真正嘗試時,你會看到它們都返回 `16` 。:
```
>>> squares[2]()
16
>>> squares[4]()
16
```
發生這種情況是因為 `x` 不是lambdas的內部變量,而是在外部作用域中定義,并且在調用lambda時訪問它 - 而不是在定義它時。 在循環結束時, `x` 的值是 `4` ,所以所有的函數現在返回 `4**2` ,即 `16` 。你還可以通過更改 `x` 的值來驗證這一點,并查看lambdas的結果如何變化:
```
>>> x = 8
>>> squares[2]()
64
```
為了避免這種情況,你需要將值保存在lambdas的局部變量中,這樣它們就不依賴于全局``x`` 的值
```
>>> squares = []
>>> for x in range(5):
... squares.append(lambda n=x: n**2)
```
這里, `n=x` 在lambda本地創建一個新的變量 `n` ,并在定義lambda時計算,使它具有與 `x` 在循環中該點相同的值。這意味著 `n` 的值在第一個lambda中為 `0` ,在第二個lambda中為 `1` ,在第三個中為 `2` ,依此類推。因此每個lambda現在將返回正確的結果:
```
>>> squares[2]()
4
>>> squares[4]()
16
```
請注意,這種行為并不是lambda所特有的,但也適用于常規函數。
### [如何跨模塊共享全局變量?](#id12)
在單個程序中跨模塊共享信息的規范方法是創建一個特殊模塊(通常稱為config或cfg)。只需在應用程序的所有模塊中導入配置模塊;然后該模塊可用作全局名稱。因為每個模塊只有一個實例,所以對模塊對象所做的任何更改都會在任何地方反映出來。 例如:
config.py:
```
x = 0 # Default value of the 'x' configuration setting
```
mod.py:
```
import config
config.x = 1
```
main.py:
```
import config
import mod
print(config.x)
```
請注意,出于同樣的原因,使用模塊也是實現Singleton設計模式的基礎。
### [導入模塊的“最佳實踐”是什么?](#id13)
通常,不要使用 `from modulename import *` 。這樣做會使導入器的命名空間變得混亂,并且使得連接器更難以檢測未定義的名稱。
在文件的頂部導入模塊。這樣做可以清楚地了解代碼所需的其他模塊,并避免了模塊名稱是否在范圍內的問題。每行導入一個模塊可以輕松添加和刪除導入的模塊,但每行導入多個模塊會占用更少的屏幕空間。
如果按以下順序導入模塊,這是一種很好的做法:
1. 標準庫模塊 -- 例如: `sys`, `os`, `getopt`, `re`
2. 第三方庫模塊(安裝在Python的site-packages目錄中的任何內容) -- 例如mx.DateTime,ZODB,PIL.Image等
3. 本地開發的模塊
有時需要將模塊導入語句移動到函數或類里面,以避免循環導入問題。Gordon McMillan 說:
> 當兩個模塊都使用 "import <module>" 的導入形式時,循環導入就可以了。但是當第二個模塊想從第一個模塊中獲取一個名稱(“來自模塊導入名稱”)并且導入位于頂層時,就會出錯。這是因為第一個模塊中的名稱還不可用,因為第一個模塊正在忙著導入第二個模塊。
在這種情況下,如果第二個模塊僅用于一個函數,則可以輕松地將模塊導入語句移動到該函數中。調用導入時,第一個模塊將完成初始化,第二個模塊可以進行導入。
如果某些模塊是特定于平臺的,則可能還需要將模塊導入語句移出頂級代碼。在這種情況下,甚至可能無法導入文件頂部的所有模塊。在這種情況下,在相應的特定于平臺的代碼中導入正確的模塊是一個很好的選擇。
只有當需要解決諸如避免循環導入或試圖減少模塊初始化時間的問題時,才可以將導入移動到本地范圍,例如在函數定義中。如果根據程序的執行方式,許多導入是不必要的,這種技術尤其有用。如果僅在某個函數中使用模塊,您還可能希望將導入移到該函數中。請注意,第一次加載模塊可能會因為模塊的一次初始化而代價高昂,但多次加載模塊實際上是免費的,只需進行幾次字典查找。即使模塊名稱超出了作用域,模塊也可能在 [`sys.modules`](../library/sys.xhtml#sys.modules "sys.modules") 中可用。
### [為什么對象之間共享默認值?](#id14)
這種類型的缺陷通常會惹惱新手程序員。考慮這個函數
```
def foo(mydict={}): # Danger: shared reference to one dict for all calls
... compute something ...
mydict[key] = value
return mydict
```
第一次調用此函數時,`mydict` 包含一個項目。第二次,`mydict``包含兩個項目,因為當 ``foo()` 開始執行時, `mydict` 已有一個項目。
It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.
By definition, immutable objects such as numbers, strings, tuples, and `None`, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.
Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use `None` as the default value and inside the function, check if the parameter is `None` and create a new list/dictionary/whatever if it is. For example, don't write:
```
def foo(mydict={}):
...
```
但是:
```
def foo(mydict=None):
if mydict is None:
mydict = {} # create a new dict for local namespace
```
This feature can be useful. When you have a function that's time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called "memoizing", and can be implemented like this:
```
# Callers can only provide two parameters and optionally pass _cache by keyword
def expensive(arg1, arg2, *, _cache={}):
if (arg1, arg2) in _cache:
return _cache[(arg1, arg2)]
# Calculate the value
result = ... expensive computation ...
_cache[(arg1, arg2)] = result # Store result in the cache
return result
```
You could use a global variable containing a dictionary instead of the default value; it's a matter of taste.
### [如何將可選參數或關鍵字參數從一個函數傳遞到另一個函數?](#id15)
使用函數參數列表中的 `*` 和 `**` 說明符收集參數;這會將位置參數作為元組,將關鍵字參數作為字典。然后,您可以使用 `*` 和 `**` 調用另一個函數時傳遞這些參數:
```
def f(x, *args, **kwargs):
...
kwargs['width'] = '14.3c'
...
g(x, *args, **kwargs)
```
### [形參和實參之間有什么區別?](#id16)
[Parameters](../glossary.xhtml#term-parameter) are defined by the names that appear in a function definition, whereas [arguments](../glossary.xhtml#term-argument) are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
```
def func(foo, bar=None, **kwargs):
pass
```
*foo*, *bar* 和 *kwargs* 是 `func` 的參數。但是,在調用 `func` 時,例如:
```
func(42, bar=314, extra=somevar)
```
the values `42`, `314`, and `somevar` are arguments.
### [為什么更改列表'y'也會更改列表'x'?](#id17)
如果你編寫的代碼就像下面一樣:
```
>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]
```
你可能想知道為什么追加一個元素也改變了x。
產生這種結果有兩個因素:
1. Variables are simply names that refer to objects. Doing `y = x` doesn't create a copy of the list -- it creates a new variable `y` that refers to the same object `x` refers to. This means that there is only one object (the list), and both `x` and `y` refer to it.
2. Lists are [mutable](../glossary.xhtml#term-mutable), which means that you can change their content.
After the call to `append()`, the content of the mutable object has changed from `[]` to `[10]`. Since both the variables refer to the same object, using either name accesses the modified value `[10]`.
如果我們改為將不可變對象分配給 `x`:
```
>>> x = 5 # ints are immutable
>>> y = x
>>> x = x + 1 # 5 can't be mutated, we are creating a new object here
>>> x
6
>>> y
5
```
we can see that in this case `x` and `y` are not equal anymore. This is because integers are [immutable](../glossary.xhtml#term-immutable), and when we do `x = x + 1` we are not mutating the int `5` by incrementing its value; instead, we are creating a new object (the int `6`) and assigning it to `x` (that is, changing which object `x` refers to). After this assignment we have two objects (the ints `6` and `5`) and two variables that refer to them (`x` now refers to `6` but `y` still refers to `5`).
Some operations (for example `y.append(10)` and `y.sort()`) mutate the object, whereas superficially similar operations (for example `y = y + [10]`and `sorted(y)`) create a new object. In general in Python (and in all cases in the standard library) a method that mutates an object will return `None`to help avoid getting the two types of operations confused. So if you mistakenly write `y.sort()` thinking it will give you a sorted copy of `y`, you'll instead end up with `None`, which will likely cause your program to generate an easily diagnosed error.
However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, `+=` mutates lists but not tuples or ints (
```
a_list
+= [1, 2, 3]
```
is equivalent to `a_list.extend([1, 2, 3])` and mutates `a_list`, whereas `some_tuple += (1, 2, 3)` and `some_int += 1` create new objects).
換而言之:
- If we have a mutable object ([`list`](../library/stdtypes.xhtml#list "list"), [`dict`](../library/stdtypes.xhtml#dict "dict"), [`set`](../library/stdtypes.xhtml#set "set"), etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change.
- If we have an immutable object ([`str`](../library/stdtypes.xhtml#str "str"), [`int`](../library/functions.xhtml#int "int"), [`tuple`](../library/stdtypes.xhtml#tuple "tuple"), etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.
If you want to know if two variables refer to the same object or not, you can use the [`is`](../reference/expressions.xhtml#is) operator, or the built-in function [`id()`](../library/functions.xhtml#id "id").
### [如何編寫帶輸出參數的函數(通過引用調用)?](#id18)
Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there's no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways.
1. By returning a tuple of the results:
```
def func2(a, b):
a = 'new-value' # a and b are local names
b = b + 1 # assigned to new objects
return a, b # return new values
x, y = 'old-value', 99
x, y = func2(x, y)
print(x, y) # output: new-value 100
```
This is almost always the clearest solution.
2. By using global variables. This isn't thread-safe, and is not recommended.
3. By passing a mutable (changeable in-place) object:
```
def func1(a):
a[0] = 'new-value' # 'a' references a mutable list
a[1] = a[1] + 1 # changes a shared object
args = ['old-value', 99]
func1(args)
print(args[0], args[1]) # output: new-value 100
```
4. By passing in a dictionary that gets mutated:
```
def func3(args):
args['a'] = 'new-value' # args is a mutable dictionary
args['b'] = args['b'] + 1 # change it in-place
args = {'a': 'old-value', 'b': 99}
func3(args)
print(args['a'], args['b'])
```
5. Or bundle up values in a class instance:
```
class callByRef:
def __init__(self, **args):
for (key, value) in args.items():
setattr(self, key, value)
def func4(args):
args.a = 'new-value' # args is a mutable callByRef
args.b = args.b + 1 # change object in-place
args = callByRef(a='old-value', b=99)
func4(args)
print(args.a, args.b)
```
There's almost never a good reason to get this complicated.
Your best choice is to return a tuple containing the multiple results.
### [如何在Python中創建高階函數?](#id19)
You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define `linear(a,b)` which returns a function `f(x)` that computes the value `a*x+b`. Using nested scopes:
```
def linear(a, b):
def result(x):
return a * x + b
return result
```
Or using a callable object:
```
class linear:
def __init__(self, a, b):
self.a, self.b = a, b
def __call__(self, x):
return self.a * x + self.b
```
In both cases,
```
taxes = linear(0.3, 2)
```
gives a callable object where `taxes(10e6) == 0.3 * 10e6 + 2`.
The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:
```
class exponential(linear):
# __init__ inherited
def __call__(self, x):
return self.a * (x ** self.b)
```
Object can encapsulate state for several methods:
```
class counter:
value = 0
def set(self, x):
self.value = x
def up(self):
self.value = self.value + 1
def down(self):
self.value = self.value - 1
count = counter()
inc, dec, reset = count.up, count.down, count.set
```
Here `inc()`, `dec()` and `reset()` act like functions which share the same counting variable.
### [如何在Python中復制對象?](#id20)
In general, try [`copy.copy()`](../library/copy.xhtml#copy.copy "copy.copy") or [`copy.deepcopy()`](../library/copy.xhtml#copy.deepcopy "copy.deepcopy") for the general case. Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a [`copy()`](../library/stdtypes.xhtml#dict.copy "dict.copy")method:
```
newdict = olddict.copy()
```
Sequences can be copied by slicing:
```
new_l = l[:]
```
### [如何找到對象的方法或屬性?](#id21)
For an instance x of a user-defined class, `dir(x)` returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.
### [我的代碼如何才能發現對象的名稱?](#id22)
Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; The same is true of `def` and `class` statements, but in that case the value is a callable. Consider the following code:
```
>>> class A:
... pass
...
>>> B = A
>>> a = B()
>>> b = a
>>> print(b)
<__main__.A object at 0x16D07CC>
>>> print(a)
<__main__.A object at 0x16D07CC>
```
Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value.
Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.
In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:
> The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)...
>
> ....and don't be surprised if you'll find that it's known by many names, or no name at all!
### [逗號運算符的優先級是什么?](#id23)
Comma is not an operator in Python. Consider this session:
```
>>> "a" in "b", "a"
(False, 'a')
```
Since the comma is not an operator, but a separator between expressions the above is evaluated as if you had entered:
```
("a" in "b"), "a"
```
not:
```
"a" in ("b", "a")
```
The same is true of the various assignment operators (`=`, `+=` etc). They are not truly operators but syntactic delimiters in assignment statements.
### [Is there an equivalent of C's "?:" ternary operator?](#id24)
Yes, there is. The syntax is as follows:
```
[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y
```
Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:
```
[expression] and [on_true] or [on_false]
```
However, this idiom is unsafe, as it can give wrong results when *on\_true*has a false boolean value. Therefore, it is always better to use the `... if ... else ...` form.
### [Is it possible to write obfuscated one-liners in Python?](#id25)
Yes. Usually this is done by nesting [`lambda`](../reference/expressions.xhtml#lambda) within `lambda`. See the following three examples, due to Ulf Bartelt:
```
from functools import reduce
# Primes < 1000
print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))
# First 10 Fibonacci numbers
print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
f(x,f), range(10))))
# Mandelbrot set
print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
# \___ ___/ \___ ___/ | | |__ lines on screen
# V V | |______ columns on screen
# | | |__________ maximum of "iterations"
# | |_________________ range on y axis
# |____________________________ range on x axis
```
Don't try this at home, kids!
### [函數參數列表中的斜杠(/)是什么意思?](#id26)
A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, [`pow()`](../library/functions.xhtml#pow "pow") is a function that accepts positional-only parameters. Its documentation looks like this:
```
>>> help(pow)
Help on built-in function pow in module builtins:
pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
```
The slash at the end of the parameter list means that all three parameters are positional-only. Thus, calling [`pow()`](../library/functions.xhtml#pow "pow") with keyword aguments would lead to an error:
```
>>> pow(x=3, y=4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pow() takes no keyword arguments
```
Note that as of this writing this is only documentational and no valid syntax in Python, although there is [**PEP 570**](https://www.python.org/dev/peps/pep-0570) \[https://www.python.org/dev/peps/pep-0570\], which proposes a syntax for position-only parameters in Python.
## [數字和字符串](#id27)
### [如何指定十六進制和八進制整數?](#id28)
To specify an octal digit, precede the octal value with a zero, and then a lower or uppercase "o". For example, to set the variable "a" to the octal value "10" (8 in decimal), type:
```
>>> a = 0o10
>>> a
8
```
Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase "x". Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter:
```
>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178
```
### [為什么-22 // 10返回-3?](#id29)
It's primarily driven by the desire that `i % j` have the same sign as `j`. If you want that, and also want:
```
i == (i // j) * j + (i % j)
```
then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate `i // j` need to make `i % j` have the same sign as `i`.
There are few real use cases for `i % j` when `j` is negative. When `j`is positive, there are many, and in virtually all of them it's more useful for `i % j` to be `>= 0`. If the clock says 10 now, what did it say 200 hours ago? `-190 % 12 == 2` is useful; `-190 % 12 == -10` is a bug waiting to bite.
### [如何將字符串轉換為數字?](#id30)
For integers, use the built-in [`int()`](../library/functions.xhtml#int "int") type constructor, e.g.
```
int('144')
== 144
```
. Similarly, [`float()`](../library/functions.xhtml#float "float") converts to floating-point, e.g. `float('144') == 144.0`.
By default, these interpret the number as decimal, so that
```
int('0144') ==
144
```
and `int('0x144')` raises [`ValueError`](../library/exceptions.xhtml#ValueError "ValueError"). `int(string, base)` takes the base to convert from as a second optional argument, so
```
int('0x144', 16) ==
324
```
. If the base is specified as 0, the number is interpreted using Python's rules: a leading '0o' indicates octal, and '0x' indicates a hex number.
Do not use the built-in function [`eval()`](../library/functions.xhtml#eval "eval") if all you need is to convert strings to numbers. [`eval()`](../library/functions.xhtml#eval "eval") will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass `__import__('os').system("rm -rf $HOME")` which would erase your home directory.
[`eval()`](../library/functions.xhtml#eval "eval") also has the effect of interpreting numbers as Python expressions, so that e.g. `eval('09')` gives a syntax error because Python does not allow leading '0' in a decimal number (except '0').
### [如何將數字轉換為字符串?](#id31)
To convert, e.g., the number 144 to the string '144', use the built-in type constructor [`str()`](../library/stdtypes.xhtml#str "str"). If you want a hexadecimal or octal representation, use the built-in functions [`hex()`](../library/functions.xhtml#hex "hex") or [`oct()`](../library/functions.xhtml#oct "oct"). For fancy formatting, see the [格式化字符串字面值](../reference/lexical_analysis.xhtml#f-strings) and [格式字符串語法](../library/string.xhtml#formatstrings) sections, e.g. `"{:04d}".format(144)` yields `'0144'` and `"{:.3f}".format(1.0/3.0)` yields `'0.333'`.
### [如何修改字符串?](#id32)
You can't, because strings are immutable. In most situations, you should simply construct a new string from the various parts you want to assemble it from. However, if you need an object with the ability to modify in-place unicode data, try using an [`io.StringIO`](../library/io.xhtml#io.StringIO "io.StringIO") object or the [`array`](../library/array.xhtml#module-array "array: Space efficient arrays of uniformly typed numeric values.")module:
```
>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello, world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello, there!'
>>> import array
>>> a = array.array('u', s)
>>> print(a)
array('u', 'Hello, world')
>>> a[0] = 'y'
>>> print(a)
array('u', 'yello, world')
>>> a.tounicode()
'yello, world'
```
### [如何使用字符串調用函數/方法?](#id33)
有各種技術。
- The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:
```
def a():
pass
def b():
pass
dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
dispatch[get_input()]() # Note trailing parens to call function
```
- Use the built-in function [`getattr()`](../library/functions.xhtml#getattr "getattr"):
```
import foo
getattr(foo, 'bar')()
```
Note that [`getattr()`](../library/functions.xhtml#getattr "getattr") works on any object, including classes, class instances, modules, and so on.
This is used in several places in the standard library, like this:
```
class Foo:
def do_foo(self):
...
def do_bar(self):
...
f = getattr(foo_instance, 'do_' + opname)
f()
```
- Use [`locals()`](../library/functions.xhtml#locals "locals") or [`eval()`](../library/functions.xhtml#eval "eval") to resolve the function name:
```
def myFunc():
print("hello")
fname = "myFunc"
f = locals()[fname]
f()
f = eval(fname)
f()
```
Note: Using [`eval()`](../library/functions.xhtml#eval "eval") is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.
### [Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?](#id34)
You can use `S.rstrip("\r\n")` to remove all occurrences of any line terminator from the end of the string `S` without removing other trailing whitespace. If the string `S` represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:
```
>>> lines = ("line 1 \r\n"
... "\r\n"
... "\r\n")
>>> lines.rstrip("\n\r")
'line 1 '
```
Since this is typically only desired when reading text one line at a time, using `S.rstrip()` this way works well.
### [Is there a scanf() or sscanf() equivalent?](#id35)
Not as such.
For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the [`split()`](../library/stdtypes.xhtml#str.split "str.split") method of string objects and then convert decimal strings to numeric values using [`int()`](../library/functions.xhtml#int "int") or [`float()`](../library/functions.xhtml#float "float"). `split()` supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator.
For more complicated input parsing, regular expressions are more powerful than C's `sscanf()` and better suited for the task.
### [What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?](#id36)
見 [Unicode 指南](../howto/unicode.xhtml#unicode-howto)
## [性能](#id37)
### [我的程序太慢了。該如何加快速度?](#id38)
That's a tough one, in general. First, here are a list of things to remember before diving further:
- Performance characteristics vary across Python implementations. This FAQ focusses on [CPython](../glossary.xhtml#term-cpython).
- Behaviour can vary across operating systems, especially when talking about I/O or multi-threading.
- You should always find the hot spots in your program *before* attempting to optimize any code (see the [`profile`](../library/profile.xhtml#module-profile "profile: Python source profiler.") module).
- Writing benchmark scripts will allow you to iterate quickly when searching for improvements (see the [`timeit`](../library/timeit.xhtml#module-timeit "timeit: Measure the execution time of small code snippets.") module).
- It is highly recommended to have good code coverage (through unit testing or any other technique) before potentially introducing regressions hidden in sophisticated optimizations.
That being said, there are many tricks to speed up Python code. Here are some general principles which go a long way towards reaching acceptable performance levels:
- Making your algorithms faster (or changing to faster ones) can yield much larger benefits than trying to sprinkle micro-optimization tricks all over your code.
- Use the right data structures. Study documentation for the [內置類型](../library/stdtypes.xhtml#bltin-types)and the [`collections`](../library/collections.xhtml#module-collections "collections: Container datatypes") module.
- When the standard library provides a primitive for doing something, it is likely (although not guaranteed) to be faster than any alternative you may come up with. This is doubly true for primitives written in C, such as builtins and some extension types. For example, be sure to use either the [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") built-in method or the related [`sorted()`](../library/functions.xhtml#sorted "sorted")function to do sorting (and see the [排序指南](../howto/sorting.xhtml#sortinghowto) for examples of moderately advanced usage).
- Abstractions tend to create indirections and force the interpreter to work more. If the levels of indirection outweigh the amount of useful work done, your program will be slower. You should avoid excessive abstraction, especially under the form of tiny functions or methods (which are also often detrimental to readability).
If you have reached the limit of what pure Python can allow, there are tools to take you further away. For example, [Cython](http://cython.org) \[http://cython.org\] can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms. Cython can take advantage of compilation (and optional type annotations) to make your code significantly faster than when interpreted. If you are confident in your C programming skills, you can also [write a C extension module](../extending/index.xhtml#extending-index)yourself.
參見
The wiki page devoted to [performance tips](https://wiki.python.org/moin/PythonSpeed/PerformanceTips) \[https://wiki.python.org/moin/PythonSpeed/PerformanceTips\].
### [將多個字符串連接在一起的最有效方法是什么?](#id39)
[`str`](../library/stdtypes.xhtml#str "str") and [`bytes`](../library/stdtypes.xhtml#bytes "bytes") objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.
To accumulate many [`str`](../library/stdtypes.xhtml#str "str") objects, the recommended idiom is to place them into a list and call [`str.join()`](../library/stdtypes.xhtml#str.join "str.join") at the end:
```
chunks = []
for s in my_strings:
chunks.append(s)
result = ''.join(chunks)
```
(another reasonably efficient idiom is to use [`io.StringIO`](../library/io.xhtml#io.StringIO "io.StringIO"))
To accumulate many [`bytes`](../library/stdtypes.xhtml#bytes "bytes") objects, the recommended idiom is to extend a [`bytearray`](../library/stdtypes.xhtml#bytearray "bytearray") object using in-place concatenation (the `+=` operator):
```
result = bytearray()
for b in my_bytes_objects:
result += b
```
## [序列(元組/列表)](#id40)
### [如何在元組和列表之間進行轉換?](#id41)
The type constructor `tuple(seq)` converts any sequence (actually, any iterable) into a tuple with the same items in the same order.
For example, `tuple([1, 2, 3])` yields `(1, 2, 3)` and `tuple('abc')`yields `('a', 'b', 'c')`. If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call [`tuple()`](../library/stdtypes.xhtml#tuple "tuple") when you aren't sure that an object is already a tuple.
The type constructor `list(seq)` converts any sequence or iterable into a list with the same items in the same order. For example, `list((1, 2, 3))` yields `[1, 2, 3]` and `list('abc')` yields `['a', 'b', 'c']`. If the argument is a list, it makes a copy just like `seq[:]` would.
### [什么是負數序號?](#id42)
Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of `seq[-n]` as the same as `seq[len(seq)-n]`.
Using negative indices can be very convenient. For example `S[:-1]` is all of the string except for its last character, which is useful for removing the trailing newline from a string.
### [如何以相反的順序迭代序列?](#id43)
Use the [`reversed()`](../library/functions.xhtml#reversed "reversed") built-in function, which is new in Python 2.4:
```
for x in reversed(sequence):
... # do something with x ...
```
This won't touch your original sequence, but build a new copy with reversed order to iterate over.
With Python 2.3, you can use an extended slice syntax:
```
for x in sequence[::-1]:
... # do something with x ...
```
### [如何從列表中刪除重復項?](#id44)
See the Python Cookbook for a long discussion of many ways to do this:
> <https://code.activestate.com/recipes/52560/>
If you don't mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:
```
if mylist:
mylist.sort()
last = mylist[-1]
for i in range(len(mylist)-2, -1, -1):
if last == mylist[i]:
del mylist[i]
else:
last = mylist[i]
```
If all elements of the list may be used as set keys (i.e. they are all [hashable](../glossary.xhtml#term-hashable)) this is often faster
```
mylist = list(set(mylist))
```
This converts the list into a set, thereby removing duplicates, and then back into a list.
### [你如何在Python中創建一個數組?](#id45)
使用列表:
```
["this", 1, "is", "an", "array"]
```
Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types.
The `array` module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that the Numeric extensions and others define array-like structures with various characteristics as well.
To get Lisp-style linked lists, you can emulate cons cells using tuples:
```
lisp_list = ("like", ("this", ("example", None) ) )
```
If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is `lisp_list[0]` and the analogue of cdr is `lisp_list[1]`. Only do this if you're sure you really need to, because it's usually a lot slower than using Python lists.
### [如何創建多維列表?](#id46)
你可能試圖制作一個像這樣的多維數組:
```
>>> A = [[None] * 2] * 3
```
如果你打印它,看起來是正確的:
```
>>> A
[[None, None], [None, None], [None, None]]
```
但是,當您分配值時,它會顯示在多個位置:
```
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]
```
The reason is that replicating a list with `*` doesn't create copies, it only creates references to the existing objects. The `*3` creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.
The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list:
```
A = [None] * 3
for i in range(3):
A[i] = [None] * 2
```
This generates a list containing 3 different lists of length two. You can also use a list comprehension:
```
w, h = 2, 3
A = [[None] * w for i in range(h)]
```
Or, you can use an extension that provides a matrix datatype; [NumPy](http://www.numpy.org/) \[http://www.numpy.org/\] is the best known.
### [如何將方法應用于一系列對象?](#id47)
Use a list comprehension:
```
result = [obj.method() for obj in mylist]
```
### [Why does a\_tuple\[i\] += \['item'\] raise an exception when the addition works?](#id48)
This is because of a combination of the fact that augmented assignment operators are *assignment* operators, and the difference between mutable and immutable objects in Python.
This discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects, but we'll use a `list` and `+=` as our exemplar.
If you wrote:
```
>>> a_tuple = (1, 2)
>>> a_tuple[0] += 1
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
```
The reason for the exception should be immediately clear: `1` is added to the object `a_tuple[0]` points to (`1`), producing the result object, `2`, but when we attempt to assign the result of the computation, `2`, to element `0` of the tuple, we get an error because we can't change what an element of a tuple points to.
Under the covers, what this augmented assignment statement is doing is approximately this:
```
>>> result = a_tuple[0] + 1
>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
```
It is the assignment part of the operation that produces the error, since a tuple is immutable.
When you write something like:
```
>>> a_tuple = (['foo'], 'bar')
>>> a_tuple[0] += ['item']
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
```
The exception is a bit more surprising, and even more surprising is the fact that even though there was an error, the append worked:
```
>>> a_tuple[0]
['foo', 'item']
```
To see why this happens, you need to know that (a) if an object implements an `__iadd__` magic method, it gets called when the `+=` augmented assignment is executed, and its return value is what gets used in the assignment statement; and (b) for lists, `__iadd__` is equivalent to calling `extend` on the list and returning the list. That's why we say that for lists, `+=` is a "shorthand" for `list.extend`:
```
>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]
```
This is equivalent to:
```
>>> result = a_list.__iadd__([1])
>>> a_list = result
```
The object pointed to by a\_list has been mutated, and the pointer to the mutated object is assigned back to `a_list`. The end result of the assignment is a no-op, since it is a pointer to the same object that `a_list`was previously pointing to, but the assignment still happens.
Thus, in our tuple example what is happening is equivalent to:
```
>>> result = a_tuple[0].__iadd__(['item'])
>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment
```
The `__iadd__` succeeds, and thus the list is extended, but even though `result` points to the same object that `a_tuple[0]` already points to, that final assignment still results in an error, because tuples are immutable.
### [I want to do a complicated sort: can you do a Schwartzian Transform in Python?](#id49)
The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its "sort value". In Python, use the `key` argument for the [`list.sort()`](../library/stdtypes.xhtml#list.sort "list.sort") method:
```
Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))
```
### [如何按其他列表中的值對一個列表進行排序?](#id50)
Merge them into an iterator of tuples, sort the resulting list, and then pick out the element you want.
```
>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'something']
```
An alternative for the last step is:
```
>>> result = []
>>> for p in pairs: result.append(p[1])
```
If you find this more legible, you might prefer to use this instead of the final list comprehension. However, it is almost twice as slow for long lists. Why? First, the `append()` operation has to reallocate memory, and while it uses some tricks to avoid doing that each time, it still has to do it occasionally, and that costs quite a bit. Second, the expression "result.append" requires an extra attribute lookup, and third, there's a speed reduction from having to make all those function calls.
## [對象](#id51)
### [什么是類?](#id52)
A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype.
A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic `Mailbox` class that provides basic accessor methods for a mailbox, and subclasses such as `MboxMailbox`, `MaildirMailbox`, `OutlookMailbox`that handle various specific mailbox formats.
### [What is a method?](#id53)
A method is a function on some object `x` that you normally call as `x.name(arguments...)`. Methods are defined as functions inside the class definition:
```
class C:
def meth(self, arg):
return arg * 2 + self.attribute
```
### [什么是self?](#id54)
Self is merely a conventional name for the first argument of a method. A method defined as `meth(self, a, b, c)` should be called as `x.meth(a, b, c)` for some instance `x` of the class in which the definition occurs; the called method will think it is called as `meth(x, a, b, c)`.
另請參閱 [為什么必須在方法定義和調用中顯式使用“self”?](design.xhtml#why-self) 。
### [如何檢查對象是否是給定類或其子類的實例?](#id55)
Use the built-in function `isinstance(obj, cls)`. You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. `isinstance(obj, (class1, class2, ...))`, and can also check whether an object is one of Python's built-in types, e.g. `isinstance(obj, str)` or `isinstance(obj, (int, float, complex))`.
Note that most programs do not use [`isinstance()`](../library/functions.xhtml#isinstance "isinstance") on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object's class and doing a different thing based on what class it is. For example, if you have a function that does something:
```
def search(obj):
if isinstance(obj, Mailbox):
... # code to search a mailbox
elif isinstance(obj, Document):
... # code to search a document
elif ...
```
A better approach is to define a `search()` method on all the classes and just call it:
```
class Mailbox:
def search(self):
... # code to search a mailbox
class Document:
def search(self):
... # code to search a document
obj.search()
```
### [什么是代理?](#id56)
Delegation is an object oriented technique (also called a design pattern). Let's say you have an object `x` and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of `x`.
Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase:
```
class UpperOut:
def __init__(self, outfile):
self._outfile = outfile
def write(self, s):
self._outfile.write(s.upper())
def __getattr__(self, name):
return getattr(self._outfile, name)
```
Here the `UpperOut` class redefines the `write()` method to convert the argument string to uppercase before calling the underlying `self.__outfile.write()` method. All other methods are delegated to the underlying `self.__outfile` object. The delegation is accomplished via the `__getattr__` method; consult [the language reference](../reference/datamodel.xhtml#attribute-access)for more information about controlling attribute access.
Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a [`__setattr__()`](../reference/datamodel.xhtml#object.__setattr__ "object.__setattr__")method too, and it must do so carefully. The basic implementation of [`__setattr__()`](../reference/datamodel.xhtml#object.__setattr__ "object.__setattr__") is roughly equivalent to the following:
```
class X:
...
def __setattr__(self, name, value):
self.__dict__[name] = value
...
```
Most [`__setattr__()`](../reference/datamodel.xhtml#object.__setattr__ "object.__setattr__") implementations must modify `self.__dict__` to store local state for self without causing an infinite recursion.
### [如何從覆蓋基類的派生類調用基類中定義的方法?](#id57)
Use the built-in [`super()`](../library/functions.xhtml#super "super") function:
```
class Derived(Base):
def meth(self):
super(Derived, self).meth()
```
For version prior to 3.0, you may be using classic classes: For a class definition such as `class Derived(Base): ...` you can call method `meth()`defined in `Base` (or one of `Base`'s base classes) as
```
Base.meth(self,
arguments...)
```
. Here, `Base.meth` is an unbound method, so you need to provide the `self` argument.
### [如何組織代碼以便更改基類?](#id58)
You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. Example:
```
BaseAlias = <real base class>
class Derived(BaseAlias):
def meth(self):
BaseAlias.meth(self)
...
```
### [如何創建靜態類數據和靜態類方法?](#id59)
Both static data and static methods (in the sense of C++ or Java) are supported in Python.
For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment:
```
class C:
count = 0 # number of times C.__init__ called
def __init__(self):
C.count = C.count + 1
def getcount(self):
return C.count # or return self.count
```
`c.count` also refers to `C.count` for any `c` such that
```
isinstance(c,
C)
```
holds, unless overridden by `c` itself or by some class on the base-class search path from `c.__class__` back to `C`.
Caution: within a method of C, an assignment like `self.count = 42` creates a new and unrelated instance named "count" in `self`'s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not:
```
C.count = 314
```
Static methods are possible:
```
class C:
@staticmethod
def static(arg1, arg2, arg3):
# No 'self' parameter!
...
```
However, a far more straightforward way to get the effect of a static method is via a simple module-level function:
```
def getcount():
return C.count
```
If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation.
### [如何在Python中重載構造函數(或方法)?](#id60)
This answer actually applies to all methods, but the question usually comes up first in the context of constructors.
In C++ you'd write
```
class C {
C() { cout << "No arguments\n"; }
C(int i) { cout << "Argument is " << i << "\n"; }
}
```
In Python you have to write a single constructor that catches all cases using default arguments. For example:
```
class C:
def __init__(self, i=None):
if i is None:
print("No arguments")
else:
print("Argument is", i)
```
This is not entirely equivalent, but close enough in practice.
You could also try a variable-length argument list, e.g.
```
def __init__(self, *args):
...
```
The same approach works for all method definitions.
### [I try to use \_\_spam and I get an error about \_SomeClassName\_\_spam.](#id61)
Variable names with double leading underscores are "mangled" to provide a simple but effective way to define class private variables. Any identifier of the form `__spam` (at least two leading underscores, at most one trailing underscore) is textually replaced with `_classname__spam`, where `classname` is the current class name with any leading underscores stripped.
This doesn't guarantee privacy: an outside user can still deliberately access the "\_classname\_\_spam" attribute, and private values are visible in the object's `__dict__`. Many Python programmers never bother to use private variable names at all.
### [My class defines \_\_del\_\_ but it is not called when I delete the object.](#id62)
這有幾個可能的原因。
The del statement does not necessarily call [`__del__()`](../reference/datamodel.xhtml#object.__del__ "object.__del__") -- it simply decrements the object's reference count, and if this reaches zero [`__del__()`](../reference/datamodel.xhtml#object.__del__ "object.__del__") is called.
If your data structures contain circular links (e.g. a tree where each child has a parent reference and each parent has a list of children) the reference counts will never go back to zero. Once in a while Python runs an algorithm to detect such cycles, but the garbage collector might run some time after the last reference to your data structure vanishes, so your [`__del__()`](../reference/datamodel.xhtml#object.__del__ "object.__del__") method may be called at an inconvenient and random time. This is inconvenient if you're trying to reproduce a problem. Worse, the order in which object's [`__del__()`](../reference/datamodel.xhtml#object.__del__ "object.__del__")methods are executed is arbitrary. You can run [`gc.collect()`](../library/gc.xhtml#gc.collect "gc.collect") to force a collection, but there *are* pathological cases where objects will never be collected.
Despite the cycle collector, it's still a good idea to define an explicit `close()` method on objects to be called whenever you're done with them. The `close()` method can then remove attributes that refer to subobjects. Don't call [`__del__()`](../reference/datamodel.xhtml#object.__del__ "object.__del__") directly -- [`__del__()`](../reference/datamodel.xhtml#object.__del__ "object.__del__") should call `close()` and `close()` should make sure that it can be called more than once for the same object.
Another way to avoid cyclical references is to use the [`weakref`](../library/weakref.xhtml#module-weakref "weakref: Support for weak references and weak dictionaries.") module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!).
Finally, if your [`__del__()`](../reference/datamodel.xhtml#object.__del__ "object.__del__") method raises an exception, a warning message is printed to [`sys.stderr`](../library/sys.xhtml#sys.stderr "sys.stderr").
### [如何獲取給定類的所有實例的列表?](#id63)
Python does not keep track of all instances of a class (or of a built-in type). You can program the class's constructor to keep track of all instances by keeping a list of weak references to each instance.
### [為什么 `id()` 的結果看起來不是唯一的?](#id64)
The [`id()`](../library/functions.xhtml#id "id") builtin returns an integer that is guaranteed to be unique during the lifetime of the object. Since in CPython, this is the object's memory address, it happens frequently that after an object is deleted from memory, the next freshly created object is allocated at the same position in memory. This is illustrated by this example:
```
>>> id(1000) # doctest: +SKIP
13901272
>>> id(2000) # doctest: +SKIP
13901272
```
The two ids belong to different integer objects that are created before, and deleted immediately after execution of the `id()` call. To be sure that objects whose id you want to examine are still alive, create another reference to the object:
```
>>> a = 1000; b = 2000
>>> id(a) # doctest: +SKIP
13901272
>>> id(b) # doctest: +SKIP
13891296
```
## [模塊](#id65)
### [怎么創建.pyc文件?](#id66)
When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a `.pyc` file containing the compiled code should be created in a `__pycache__` subdirectory of the directory containing the `.py` file. The `.pyc` file will have a filename that starts with the same name as the `.py` file, and ends with `.pyc`, with a middle component that depends on the particular `python`binary that created it. (See [**PEP 3147**](https://www.python.org/dev/peps/pep-3147) \[https://www.python.org/dev/peps/pep-3147\] for details.)
One reason that a `.pyc` file may not be created is a permissions problem with the directory containing the source file, meaning that the `__pycache__`subdirectory cannot be created. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server.
Unless the [`PYTHONDONTWRITEBYTECODE`](../using/cmdline.xhtml#envvar-PYTHONDONTWRITEBYTECODE) environment variable is set, creation of a .pyc file is automatic if you're importing a module and Python has the ability (permissions, free space, etc...) to create a `__pycache__`subdirectory and write the compiled module to that subdirectory.
Running Python on a top level script is not considered an import and no `.pyc` will be created. For example, if you have a top-level module `foo.py` that imports another module `xyz.py`, when you run `foo` (by typing `python foo.py` as a shell command), a `.pyc` will be created for `xyz` because `xyz` is imported, but no `.pyc` file will be created for `foo` since `foo.py` isn't being imported.
If you need to create a `.pyc` file for `foo` -- that is, to create a `.pyc` file for a module that is not imported -- you can, using the [`py_compile`](../library/py_compile.xhtml#module-py_compile "py_compile: Generate byte-code files from Python source files.") and [`compileall`](../library/compileall.xhtml#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") modules.
The [`py_compile`](../library/py_compile.xhtml#module-py_compile "py_compile: Generate byte-code files from Python source files.") module can manually compile any module. One way is to use the `compile()` function in that module interactively:
```
>>> import py_compile
>>> py_compile.compile('foo.py')
```
This will write the `.pyc` to a `__pycache__` subdirectory in the same location as `foo.py` (or you can override that with the optional parameter `cfile`).
You can also automatically compile all files in a directory or directories using the [`compileall`](../library/compileall.xhtml#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") module. You can do it from the shell prompt by running `compileall.py` and providing the path of a directory containing Python files to compile:
```
python -m compileall .
```
### [如何找到當前模塊名稱?](#id67)
A module can find out its own module name by looking at the predefined global variable `__name__`. If this has the value `'__main__'`, the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking `__name__`:
```
def main():
print('Running test...')
...
if __name__ == '__main__':
main()
```
### [怎樣才能擁有相互導入的模塊?](#id68)
假設您有以下模塊:
foo.py:
```
from bar import bar_var
foo_var = 1
```
bar.py:
```
from foo import foo_var
bar_var = 2
```
The problem is that the interpreter will perform the following steps:
- main imports foo
- Empty globals for foo are created
- foo is compiled and starts executing
- foo imports bar
- Empty globals for bar are created
- bar is compiled and starts executing
- bar imports foo (which is a no-op since there already is a module named foo)
- bar.foo\_var = foo.foo\_var
The last step fails, because Python isn't done with interpreting `foo` yet and the global symbol dictionary for `foo` is still empty.
The same thing happens when you use `import foo`, and then try to access `foo.foo_var` in global code.
There are (at least) three possible workarounds for this problem.
Guido van Rossum recommends avoiding all uses of `from <module> import ...`, and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as `<module>.<name>`.
Jim Roskind建議在每個模塊中按以下順序執行步驟:
- exports(全局變量,函數和不需要導入基類的類)
- `import` statements
- active code (including globals that are initialized from imported values).
van Rossum doesn't like this approach much because the imports appear in a strange place, but it does work.
Matthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first place.
These solutions are not mutually exclusive.
### [\_\_import\_\_('x.y.z') returns <module 'x'>; 如何獲取z?](#id69)
Consider using the convenience function [`import_module()`](../library/importlib.xhtml#importlib.import_module "importlib.import_module") from [`importlib`](../library/importlib.xhtml#module-importlib "importlib: The implementation of the import machinery.") instead:
```
z = importlib.import_module('x.y.z')
```
### [當我編輯導入的模塊并重新導入它時,更改不會顯示。為什么會這樣?](#id70)
出于效率和一致性的原因,Python僅在第一次導入模塊時讀取模塊文件。如果不這么做,在一個由許多模塊組成的程序中,每個模塊都會導入相同的基本模塊,那么基本模塊將被解析和重新解析多次。要強制重新讀取已更改的模塊,請執行以下操作:
```
import importlib
import modname
importlib.reload(modname)
```
警告:這種技術不是100%萬無一失。特別是包含如下語句的模塊
```
from modname import some_objects
```
將繼續使用舊版本的導入對象。如果模塊包含類定義,則不會更新現有的類實例以使用新的類定義。這可能導致以下矛盾行為:
```
>>> import importlib
>>> import cls
>>> c = cls.C() # Create an instance of C
>>> importlib.reload(cls)
<module 'cls' from 'cls.py'>
>>> isinstance(c, cls.C) # isinstance is false?!?
False
```
如果打印出類對象的“標識”,問題的本質就會明確:
```
>>> hex(id(c.__class__))
'0x7352a0'
>>> hex(id(cls.C))
'0x4198d0'
```
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](design.xhtml "設計和歷史常見問題") |
- [上一頁](general.xhtml "Python常見問題") |
- 
- [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