
Python
![]() | |
編程範型 | 多範式:函數式、指令式、反射式、結構化、物件導向 |
---|---|
設計者 | 吉多·范羅蘇姆 |
實作者 | Python軟體基金會 |
面市時間 | 1991年[1] |
目前版本 | ![]() |
型態系統 | 鴨子型別、動態、強型別[5]、漸進(自從3.5)[6] |
作業系統 | 跨平臺:Windows、Linux/Unix、macOS等 |
授權條款 | Python軟體基金會授權條款 |
副檔名 | .py、.pyi、.pyc、.pyd、.pyo(3.5之前)[7]、.pyw、.pyz(自從3.5)[8] |
網站 | www![]() |
主要實作產品 | |
CPython、PyPy、Stackless Python、MicroPython、CircuitPython、Pyston[9]、RustPython[10]、IronPython、Jython | |
衍生副語言 | |
Cython、RPython、Starlark[11] | |
啟發語言 | |
ABC[12]、Ada[13]、ALGOL 68[14]、APL[15]、C[16]、C++[17]、CLU[18]、Dylan[19]、Haskell[20]、Icon[21]、Java[22]、Lisp[23]、Modula-3[17]、Perl、Standard ML[15] | |
影響語言 | |
Boo、Cobra、CoffeeScript[24]、D、F#、Falcon、Genie[25]、Go、Groovy、JavaScript[26][27]、Julia[28]、Nim、Ring[29]、Ruby[30]、Swift[31] | |
Python(英國發音:/ˈpaɪθən/;美國發音:/ˈpaɪθɑːn/),是一種廣泛使用的直譯式、進階和通用的程式語言。Python支援多種程式設計範式,包括函數式、指令式、反射式、結構化和物件導向程式設計。它擁有動態型別系統和垃圾回收功能,能夠自動管理記憶體使用,並且其本身擁有一個巨大而廣泛的標準庫。它的語言結構以及物件導向的方法,旨在幫助程式設計師為小型的和大型的專案編寫邏輯清晰的程式碼。
吉多·范羅蘇姆於1980年代後期開始研發Python,作為ABC語言的後繼者,它也可以被視為採用了叫做M-表達式的中綴表示法的一種LISP方言[32]。吉多·范羅蘇姆於1991年首次釋出 Python 0.9.0[33]。Python 2.0於2000 年釋出並引入了新功能。Python 3.0於2008年釋出,它是該語言的主要修訂版,並非完全向下相容。Python 2於2020年隨2.7.18版停止支援[34]。
Python的設計哲學,強調程式碼的可讀性和簡潔的語法,尤其是使用空格縮排來劃分程式碼塊。相比於C或Java,Python讓開發者能夠用更少的代碼表達想法。
Python直譯器本身幾乎可以在所有的作業系統中執行,它的官方直譯器CPython是用C語言編寫的。Python是一個由社群驅動的自由軟體,目前由Python軟體基金會管理。Python是最受歡迎的程式語言之一[35][36][37][38]。
歷史[編輯]
Python的創始人吉多·范羅蘇姆,在1982年至1995年間,參與了荷蘭數學和電腦科學研究學會多個專案的工作[39]。1989年的聖誕節期間,他決心開發一個新的指令碼解釋程式,作為ABC語言的繼承者,並且用它替代Unix shell和C語言來進行系統管理,擔負與Amoeba作業系統之間的互動操作並進行例外處理[12]。他是BBC電視劇《Monty Python的飛行馬戲團》的愛好者,所以選取了Python作為這個程式語言的名字[40]。范羅蘇姆作為Python的主要開發者,獨自擔負這個專案的發展決策者職責,直到2018年7月12日,他宣布從終身仁慈獨裁者(BDFL)的職權上「永久休假」[41][42]。他在2019年1月至11月參與了第一屆五人掌控委員會繼續領導專案發展[43][44]。
在1991年2月,范羅蘇姆在alt.sources上釋出了最初程式碼(標記為版本0.9.0)[45],這時就已經存在了帶繼承的類、例外處理、函式和核心資料類型list
、dict
、str
等。在這個最初發行中就有了從Modula-3引進的模組系統[46],它的異常模型也類似於Modula-3[12]。在1994年1月,Python達到了版本1.0。這個發行版主要新特徵是包括了由Amrit Prem提供的函式語言程式設計工具lambda
、map
、filter
和reduce
[47]。Python 1.4增加了受Modula-3啟發的關鍵字參數,和對複數的內建支援,還包含了採取名字修飾的一種基本形式的資料隱藏[48]。
在2000年10月16日,Python 2.0發布,它介入了列表推導式,這是從函式語言程式設計語言SETL和Haskell中引入的。它還向垃圾回收系統增加了環檢測演算法,並且支援Unicode[49]。Python 2.1支援了巢狀作用域,就像其他靜態作用域語言一樣[50]。Python 2.2的重大革新是將Python的類型(用C寫成)和類(用Python寫成)統一入一個層級,使得Python的物件模型成為純粹和一致的物件導向的模型[51];還增加了迭代器[52],受CLU和Icon啟發的生成器[53],和描述器協定[54]。Python 2.4加入了集合資料類型,和函式修飾器[55]。Python 2.5加入了with
語句[56]。
在2008年12月3日,Python 3.0發布,它對語言做了較大修訂而不能完全後向相容[57]。Python 3發行包括了2to3
實用工具,它(至少部份的)自動將Python 2程式碼轉換成Python 3程式碼[58]。Python 3的很多新特性後來也被移植到舊的Python 2.6/2.7版本中[59]。
Python 2.7的產品壽命結束日期最初設定為2015年,出於對大量的現存程式碼不能前向移植到Python 3的關切,而將對它的支援延期至2020年[60][61]。隨著Python 2的產品壽命結束,2022年3月14日釋出的macOS 12.3已經徹底移除了Python 2[62]。當前只有Python 3的穩定版本3.10、3.11和預覽版本3.12正在被完全支援,但仍提供對3.7、3.8和3.9版本的安全性修正[63]。
在2022年12月,活躍的Python核心開發者選舉Pablo Galindo Salgado、Gregory P. Smith、Emily Morehouse、Brett Cannon和Thomas Wouters為2023年度「掌控委員會」的五位成員來領導這個專案[64]。
特徵與設計哲學[編輯]
Python是多範式程式語言。它完全支援結構化程式和物件導向程式設計,還有很多特徵支援函式語言程式設計和元程式設計比如元物件協定(元類和魔術方法[65])。通過擴充還可以支援很多範式,包括面向切面程式[66]、契約式設計[67]和邏輯程式[68]。
Python使用動態型別,在記憶體管理上採用參照計數和環檢測相結合的垃圾回收器[69]。它的特徵還有動態名字解析(後期繫結),即在程式執行期間繫結方法和變數的名字。
Python對遵循LISP傳統的函式語言程式設計提供了有限的支援[70],它提供了 map
、filter
和reduce
函式;列表推導式、字典、集合和生成器表達式[71]。標準庫中的模組functools
和itertools
,實現了從Haskell和Standard ML借鑑來的函數式工具[72]。
Python的設計理念是「優雅」、「明確」、「簡單」,它的一些重要準被合稱為「Python之禪」。在Python解釋器內運行import this
可以獲得完整的列表,下面舉出其中首要:
- 優美優於醜陋。明瞭優於隱晦。
- 簡單優於複雜。複雜優於凌亂。
- 扁平優於巢狀。稀疏優於稠密。
- 可讀性很重要。
Python開發者的方法論是「用一種方法,最好是只有一種方法來做一件事」,顯著不同於以Perl語言為代表的「不止一種方法去做一件事」風格。Python開發者在設計語言時,如果面臨多種選擇,一般會拒絕花俏的語法,而選擇明確沒有或者很少有歧義的語法。
范羅蘇姆認為ABC語言非常優美和強大,它沒有取得成功的原因是不開放造成的[73],故而將Python本身設計為可擴充的。Python並不把所有的特性和功能都整合到語言核心,而是提供了豐富的API和工具,以便程式設計師能夠輕鬆地使用Python、C、Cython來編寫擴充模組。Python還可以通過外界函式介面如標準庫中的ctypes等,來存取動態連結庫或共享庫中C相容資料類型並呼叫其中函式[74],以便於對用其他語言編寫的程式進行整合和封裝。
Python開發人員盡量避開不成熟或者不重要的優化。一些針對非重要部位的加快運行速度的補丁,通常不會被合併到Python的官方實現CPython中。在某些對運行速度要求很高的情況,可以使用JIT技術的Python實現或擴充[75]。
語法[編輯]
Python的設計目標之一是讓程式碼具備高度的可閱讀性。它設計時盡量使用其它語言經常使用的標點符號和英文單字,讓程式碼看起來整潔美觀。Python語句之後的分號是可選的,作為動態語言不需要書寫「聲明」語句,不同於其他的靜態語言如C、Pascal。
縮排[編輯]
Python語言利用縮排表示語句塊的開始和結束(越位規則),而非使用大括號或者某種關鍵字。增加縮排表示語句塊的開始,而減少縮排則表示語句塊的結束。根據PEP 8的規定[76],使用4個空格來表示每級縮排。[a]
使用Tab字元和其它數目的空格雖然都可以被解釋器識別,但不符合編碼規範,偏向使用Tab字元的程式員可以設定文字編輯器將Tab鍵轉換為4個空格。縮排成為了語法的一部分,並且Python開發者有意讓違反了「縮排規則」的程式不能通過解釋。
關鍵字[編輯]
Python有如下35個關鍵字或「保留字」;它們不能用作識別碼[77][78]:
- 注釋
識別碼[編輯]
識別碼就是名字,在ASCII範圍內(U+0001..U+007F),可用於識別碼的字元為:大寫字母A
至Z
和小寫字母a
至z
,底線_
以及數字0
至9
,但首字不可以用數字。有如下命名約定[80]:
_spam
(單底線開頭):弱「內部使用」標識。對於from M import *
,將不匯入所有以底線開頭的物件。spam_
(單底線結尾):為了避免與python關鍵字的命名衝突。__spam
(雙底線開頭):在命名一個類特性的時候,採用名字修飾,比如在類SpamEggs
內,__spam
將變成_SpamEggs__spam
[81]。__spam__
(雙底線開頭雙底線結尾):指那些包含在使用者控制的命名空間中的「魔術」方法或特性,比如__name__
、__doc__
、__init__
、__import__
、__file__
等。建議永遠不要將這樣的命名方式應用於自己的變數或函式。
在Python文獻中經常使用的元語法變數是spam和eggs而非傳統的foo和bar[81]。
語句和控制流[編輯]
Python的語句包括:
- 賦值語句,記號為等號
=
。Python支援並列賦值,可以同時給多個變數賦值,還可以交換兩個變數的值。[b] del
語句,遞迴的進行刪除。pass
語句,充當NOP,表示此行為空,不執行任何操作。assert
語句,用於程式調適階段時測試執行條件是否滿足。if
語句,當條件成立時執行語句塊。經常與elif
、else
配合使用。for
語句,遍歷列表、字串、字典、集合等迭代器,依次處理迭代器中的每個元素。while
語句,當條件為真時,循環執行語句塊。break
語句,從迴圈中跳出。continue
語句,越過這次迭代並繼續進行下個專案。try
語句,與except
、else
、finally
配合使用,處理在程式執行中出現的異常情況。raise
語句,丟擲一個異常。class
語句,用於定義類,它執行一塊程式碼並將它的局部命名空間附屬至一個類。def
語句,用於定義函式和方法。return
語句,用來從函式返回值。yield
語句,使用它從一個生成器中返回一個值。[c]在版本2.5之前,生成器是惰性迭代器,資訊是單向的從生成器傳遞出來的。自從版本2.5,yield
也是一個有返回值的運算子,能夠將資訊傳遞迴到生成器函式中[82]。自從版本3.3,資訊可以傳遞通過多個堆疊層級[83]。with
語句,把一塊程式碼包裹在一個上下文管理器之內。例如,在一塊程式碼執行之前取得一個鎖並且在此後釋放這個鎖,或打開一個檔案並且在此後關閉它。它允許了資源取得即初始化(RAII)式行為並可替代常見的try
/finally
慣用法[84]。import
語句,匯入一個模組或包。有三種用法:import <模块名字> [as <别名>]
,from <模块名字> import *
,from <模块名字> import <定义1> [as <别名1>], <定义2> [as <别名2>], ...
。
在Python中賦值語句所進行的操作是將一個名字繫結為到一個分立的、動態分配的物件的一個參照。因為名字的儲存位置不「包含」這個指示的值,稱它為「變數」是不準確的。這個名字可以隨後在任何時候重新繫結到極大不同的各種類型的物件上,包括字串、過程、具有資料和方法的複雜物件等等。因為名字是通用的參照持有者,給它關聯一個固定的資料類型是不合理的。但是在給定時間一個名字總是被繫結到有一個類型的某個物件上,因此這是動態型別。接連的把一個共同的值賦值給多個名字,比如x = 2; y = 2; z = 2
,導致給3個名字和1個數物件分配儲存,這3個名字都繫結到這1個數物件上。Python賦值語句的這種基礎機制,不同於傳統指令式程式語言比如C中的賦值,在這裡右手側的值被複製到給這個變數分配的儲存位置之中,等號左手側的變數名字是其符號位址,對為它聲明的類型而言分配給它的記憶體是足夠大的。
Python支援並廣泛使用例外處理作為檢測錯誤狀況和程式中其他「異常」事件的方式。Python風格提倡在可能出現錯誤狀況的任何時候都使用異常。在Python中習慣上不在使用之前對存取一個檔案或資源進行測試,而是先行嘗試使用它,再擷取存取被拒絕引發的異常。[d]
經常為此援引的格言是葛麗絲·霍普貢獻的EAFP[85]:「請求原諒比授權更容易」[86][87]。Python使用with
語句處理資源[88],在進入一個作用域的時候呼叫一個函式而在離開它的時候呼叫另一個函式。這能防止忘記移除資源並且還可處理更複雜的狀況比如異常。[e]
Python官方實現不提供尾呼叫最佳化或頭等續體,吉多·范羅蘇姆曾聲稱永遠都不會加以支援[89],目前只有第三方庫支援[90]。Python在版本2.5中通過擴充生成器,提供了對協程式功能的更好支援[82]。[f]版本3.4介入了綜合性的非同步I/O框架標準化,在其中擴充了利用子生成器委託的協程[91],這個擴充自從Python 3.8被棄用[92]。Python 3.5通過async/await語法介入了對協程的顯式支援[93]。從版本3.7開始async/await成為保留關鍵字[94]。[g]
模組是定義可以被匯入並重用於其他Python程式中的函式和類的Python正規.py
檔案[95]。import
語句找到一個模組,裝載它,如果有需要的話初始化它,並且定義用來參照這個模組中程式碼的一個名字或一些名字[96]。from...import
語句,找到、裝載、必需時初始化一個模組,接著增加模組參照到局部命名空間,允許存取其中的函式和類而不採用模組參照[96]。from ... import
支援*
選項來匯入所有參照而非指名的特定函式或類[95]。當模組被匯入的時候,__name__
變數被設定成這個模組的名字。在Python直譯器直接執行一個模組的時候,__name__
變數被設定為"__main__"
。這允許被設計用於匯入的模組增加只在模組被直接執行時候執行的程式碼[95][97]。dir()
函式返回在當前局部作用域中或參數指定的物件中的名字的列表[98]。
表達式[編輯]
Python中很多表達式與C和java類似,而另一些則與之不同。
- 在Python中,算術運算的加法
+
、減法-
、乘法*
和取模%
是與C和java相同的,但是除法的行為不同。在Python中有兩種除法,它們是下取整除法(或整數除法)//
和浮點除法/
[99] 。Python增加了指數算符**
。Python有如下必須用於整數的位運算:&
與(AND),|
或(OR),~
非(NOT),^
互斥或(XOR),>>
右移,<<
左移。自從Python 3.5[100],介入了新的@
中綴矩陣乘法算符[101],它已經用於了NumPy庫[102]。
- 在Python中,有如下比較運算:大於
>
,小於<
,等於==
,不等於!=
,小於等於<=
,大於等於>=
。==
按值比較,對比於Java,它按值比較數[103]而按參照比較物件[104](在Java中比較物件的值可以採用equals()
方法)。Python的is
、is not
算符可以用來比較物件的同一性(按參照比較),也就是比較兩個變數是否參照了同一個物件。而in
、not in
用於判斷一個物件是否屬於另外一個物件。在Python中,比較是可以連結起來的,比如a <= b <= c
。
- Python使用
and
、or
、not
表示邏輯運算與、或、非,不採用Java和C中所用的符號&&
、||
、!
。
- 自從Python 3.8,介入了「賦值表達式」語法
:=
。它也叫做「命名表達式」或「海象」,它將一個表達式賦值給一個識別碼,同時還返回這個表達式的值,常用作更大的表達式的一部份[105]。
- 自從Python 3.9,介入了字典合併算符
|
和更新算符|=
[106]。
- Python的匿名函式實現為
lambda
表達式。匿名函式體只能是一個表達式。[k] - Python的條件表達式表示為
x if c else y
。意思是當c
為真時,表達式的值為x
,否則表達式的值為y
。 在運算數的次序上不同於很多其他語言中常見的c ? x : y
。
- Python區分列表(list)和元組(tuple)兩種類型。列表的寫法是
[1,2,3]
,而元組的寫法是(1,2,3)
。在沒有歧義的情況下,元組的圓括號是可選的,一個元素的元組向這個元素尾隨一個逗號例如(1,)
[107]。列表是可變的,並且不能用作字典的鍵(Python中字典的鍵必須是不可變的)。元組是不可變的,因而可以用作字典的鍵,假定這個元組的所有元素都是不可變的話。可以使用+
算符來串接二個元組,這不會直接修改它們的內容,而是產生包含給定元組二者的元素的一個新元組。因此,給定變數t
初始時等於(1, 2, 3)
,執行t = t + (4, 5)
時,首先求值t + (4, 5)
,它產生(1, 2, 3, 4, 5)
,接著賦值回到t
,這在效果上「修改了」t
的內容,儘管這還是遵守了元組物件的不可變本性。
- Python有「序列解包」特徵,多個表達式,其中每個都可求值成能被賦值的東西(變數、可寫的屬性等),以與形成元組文字(literal)相同的方式,關聯起來作為一個整體,放置在賦值語句等號的左手側。這個語句預期在等號的右手側有一個「可迭代」物件,在迭代它的時候產生同左手側給出的可寫表達式相同數目的值,這個語句對它進行迭代並把每個產生的值賦值給左手側對應的表達式[108]。這個特徵允許從一個單一函式返回多個值。自從Python 3.5,增加了在表達式列表中的「可迭代解包」
*
和在字典顯示中的「字典解包」**
。[l] - Python擁有「字串格式」算符
%
。這個功能類同於C中的printf
格式化字串,比如"spam=%s eggs=%d" % ("blah", 2)
求值成"spam=blah eggs=2"
。在Python 3和2.6+中,這通過str
類的format()
方法來提供,比如"spam={0} eggs={1}".format("blah", 2)
。Python 3.6增加了「f-字串」[109]:blah = "blah"; eggs = 2; f'spam={blah} eggs={eggs}'
。[m] - Python擁有各種字串文字:
- Python允許連續出現和只用空白分隔(包括換行)的字串文字(可能使用了不同的參照約定),它們被聚合成一個單一的更長的字串[110]。[p]
- Python擁有在列表上的陣列索引和陣列分片表達式,表示為
a[key]
、a[start:stop]
或a[start:stop:step]
。索引是基於零的,負數是相對於結尾的。分片從「開始」(start)索引直到但不包括「停止」(stop)索引。分片的第三個參數叫做「步長」(step)或「間隔」(stride),允許元素被跳過和用負數指示反向。分片索引可以省略,例如a[:]
,這返回整個列表的一個複本。[q]分片的每個元素都是淺層複製的。
在Python中,在表達式和語句之間的區別是嚴格強制性的,對比於語言如Common Lisp、Scheme或Ruby。這導致重複了某些功能。比如:列表推導式對當for
迴圈。條件表達式對當if
塊。eval()
對當exec()
內建函式(在Python 2中,exec
是語句);前者用於表達式,後者用於語句。
語句不能成為表達式的一部份,所以列表和其他推導式或lambda表達式,都是表達式,不能包含語句。這個限制的一個特定情況是賦值語句比如a = 1
,不能形成條件語句的條件表達式的一部份。這能夠避免一個經典的C錯誤,即在條件中把等於算符==
誤寫為賦值算符=
,if (c = 1) { ... }
在語法上是有效(但可能非預期)的C程式碼,而if c = 1: ...
在Python中導致一個語法錯誤。
函式[編輯]
Python的函式支援遞迴和閉包[r]及其他頭等函式特徵,但不支援函式多載。Python的函式作為頭等物件,具有和普通物件平等的地位。Python的函式實際參數與形式參數之間的結合是傳遞「物件的參照」,就是把形式參數名字繫結到實際參數名字所參照的物件上。如果形式參數繫結到一個可變的物件,則通過形式參數對此物件內容的修改,在函式外也是可見的。如果形式參數繫結到一個不可變的物件,則通過形式參數是不能修改此物件內容,但可以把形式參數重新繫結到其它物件上,這並不影響函式外的物件的值。[s]
Python的變數有函式作用域、模組作用域和全域作用域。簡單存取(不賦值)一個變數的時候,名字解析服從窄到寬的LEGB(局部、包圍、全域、內建)順位規則。在函式中賦值一個變數將導致它成為這個函式的局部變數,就是說它的作用域在整個函式中,而不是在這個賦值之後至這個函式結束,因此在這個賦值之前參照它,不再於這個函式之外尋找同名變數而是引發一個錯誤。預設的名字解析規則可以用global
或nonlocal
關鍵字來覆蓋。global
聲明的變數是全域變數。[t]
global
可以用於巢狀的函式中。巢狀函式中還可以使用nonlocal
聲明,用於賦值到給非局部變數。[u]
Python可以指定形式參數的預設值,在函式定義時於形式參數序列中以param=value
樣式進行一次性初始化。形式參數在初始化之後保持既有繫結,函式的後續呼叫可繼續對它進行存取或變更。[v]在函式呼叫時為有預設值的形式參數提供實際參數是可選的。Python支援位置實際參數和關鍵字實際參數。函式呼叫時,實際參數可以如同C語言那樣按照位置與形式參數匹配;也可以採用命名參數(或稱為關鍵字實際參數),即kwarg=value
樣式的實際參數。使用不對應實際參數的特殊形式參數/
和*
,可以將參數序列分為唯位置參數[111]、可位置可關鍵字參數和唯關鍵字參數三部份。有預設值的形式參數之後不能跟隨無預設值的可位置形式參數。[w]在一個函式呼叫的實際參數序列中,關鍵字實際參數必須出現在位置實際參數之後。
在位置和關鍵字形式參數序列末尾可以分別有*args
或**kwargs
這樣的形式參數,它們對應於在函式呼叫時提供的,超出形式參數序列規定而無所對應的多個實際參數;在形式參數名字前加一個*
號,該形式參數args
是tuple
類型,對應可變數目的位置實際參數;在形式參數名字前加**
號,該形式參數kwargs
是dict
類型,對應可變數目的關鍵字實際參數。[x]在位置實際參數已經在一個序列類型如列表或元組的物件中的情況下,在參照它的變數前加一個*
號傳遞給函式,則其中所有元素解包為多個位置實際參數,關鍵字實際參數在字典中則加**
號來傳遞給函式。
修飾器(decorator)是用來修改一個函式、方法或類別定義的任何可呼叫Python物件。將正被定義的最初物件傳遞給修飾器,它返回一個修改後的物件,接著把它繫結到在定義中那個名字。Python修飾器部份受到Java註解的影響,而有類似的語法;修飾器語法是純粹的語法糖,使用@
作為關鍵字形成修飾詞。修飾器是一種形式的元程式設計,它們增強它們所修飾的函式或方法的行動。[y]
多個修飾器可以連結起來,通過在毗連的行上放置多個修飾詞,或者使用中間變數。[z]
函式修飾器的正規用法包括:用來建立類別方法或靜態方法[54],實現多方法,增加函式特性,跟蹤,設定先決條件和後置條件,同步[112];此外更遠大的用法包括:尾呼叫消除[113],記憶化甚至改進修飾器的寫作[114]。
為了增強程式碼的可讀性,可以在函式後書寫「文件字串」(簡稱docstrings),用於直譯函式的作用、參數的類型與意義、返回值類型與取值範圍等。可以使用內建函式help()
列印出函式的使用幫助。[aa]自從Python 3.5,開始支援類型提示[115],可以標註函式的參數與返回值[116]。此特性可方便IDE對原始碼進行更深入的分析。[ab]
物件及其方法[編輯]
Python支援大多數物件導向程式設計技術。在Python中所有東西都是物件,包括類、函式、數和模組。它允許多型性,不只是在類層級之內而且通過採用鴨子型別的方式。任何物件可以用於任何類型,只要它有適當的方法和特性(attribute)就能工作。Python天然支援類的繼承包括多重繼承,為此採用C3線性化或方法解析次序(MRO)演算法,還支援mixin。Python支援元類[117],它是增進類的功能的進階工具。
Python使用名字修飾有限的支援私有變數。物件的特性可以被提取為一個字典[118]。在Python中不強制使用存取子與變異子方法來存取資料成員的物件導向程式設計信條。就像Python提供函式語言程式設計構造但不嘗試要求參照透明性(無副作用)一樣,它提供物件系統但不要求物件導向程式設計行為。
物件的方法是附屬於這個物件的類的函式。對於正常的方法和函式,語法instance.method(arguments)
,是Class.method(instance, arguments)
的語法糖。Python的方法有顯式的self
形式參數用來存取實例資料,對比於在其他一些物件導向程式設計語言(比如C++、Java、Objective-C或Ruby)中隱式的self
或this
關鍵字[119]。在Python中,self
可以被看作是一個習慣用法,它可以被換為任何其它合法的參數名。[ac]
Python支援一些以__
開始和結束的特殊方法名,它們用於實現運算子多載和實現多種特殊功能[65]。在Python中,可以通過定義特殊方法來多載運算子,比如在一個類上定義__add__()
將允許在這個類別的實例上使用+
算符。在Python中,當一個子類的方法覆蓋了超類方法的時候,通過呼叫super().method
來呼叫與子類的self.method
方法同名超類別方法[120]。[ad]
Python允許通過使用@classmethod
和@staticmethod
修飾詞來分別建立類別方法和靜態方法。給類別方法的第一個實際參數是類物件而非對實例的self
參照。靜態方法沒有特定的第一個實際參數,實例或類物件都不固定的傳遞給靜態方法。[ae]
在Python中定義了一個或多個特殊方法__get__()
、__set__()
、__delete__()
的類可以用作描述器(descriptor)[121]。如此建立一個描述器的實例作為另一個類的一個類別成員,使得這個實例成為此另一個類的屬性(property)。使用與特性(attribute)存取相同的語法,存取一個實例物件中的這個成員屬性。[af]
Python的property
內建函式,將一個類中特殊定義的存取一個特性的那些方法包裝成的這個類的一個屬性[122]。[ag]
類型[編輯]
Python使用鴨子型別並擁有有類型的物件和無類型的變數名字。在編譯期不檢查類型約束,而寧願在一個物件上的操作出現可能的失敗,表現出這個給定物件不具有適合的類型。儘管是動態型別系統,Python卻是強型別的,禁止沒有明確定義的操作(比如加一個數到一個字串),而不是默默的去嘗試轉換使其有意義。Python支援廣泛的類型和類的內省。類型是type
的實例,可以被讀取和比較。
Python有著範圍廣泛的基本資料類型。同時具備常規的整數和浮點算術,它透明的支援任意精度算術、複數和十進位浮點數。Python支援種類繁多的字串操作。在Python中字串是不可變的,所以在其他程式語言中可能就地改變字串的字串操作比如字元替換,在Python中返回新的字串。
Python的一個非常有用方面就是搜集(或稱容器)類型的概念。一般的說,搜集是以一種易於參照或索引的方式包含其他物件的物件。Python對建立容器類型的物件有著語法上的支援。[ah]搜集有二種基本形式:序列和對映。有次序的序列類型是列表(動態陣列)、元組和字串。所有序列類型都是位置索引的(從0到長度−1),並且除了字串,都可以包含任意類型的物件,在同一個序列中包括多種類型的物件。字串和元組是不可變的,使得它們成為字典的鍵的完美候選者。在另一方面,列表是可變的,元素可以被插入、刪除、修改、添加或就地排序。
在另一方面,對映是以「字典」形式實現的無次序的類型,它將一組不可變的鍵對映到相應的元素上(非常像數學函式)。在字典中的鍵必須是不可變的Python類型,比如整數或字串,因為在底層它們是通過雜湊函式實現的。字典還是語言內部的中心,因為它們居於所有Python物件和類的核心:在變數名字(字串)和這個名字所參照的值之間的對映就儲存為字典,而這些字典可以通過物件的__dict__
特性直接存取。
集合搜集類型是在版本2.4中增加入語言核心的。集合是不包含重複項的無索引、無次序的搜集,並且實現了集合論運算比如併集、交集、相對補集、對稱差和子集測試。有二種類型的集合:可變的set
和不可變的frozenset
。集合中元素必須是可雜湊的,比如說,frozenset
可以是正規set
的元素而反之不行。Python還提供了廣泛的搜集操縱能力比如內建的包含元素檢查和通用迭代協定。
Python允許程式者使用類定義自己的類型[51],類在物件導向程式設計中是最經常使用的。類的新實例是通過呼叫這個類的構造器而建立的,而類都是元類type
的實例,type
是type
元類自身的實例,[ai]這允許了元程式設計和反射。
在版本3.0之前,Python有兩種類:舊式的和新式的[123]。二種樣式的語法是一樣的,不同在於是否直接或間接的繼承自類object
,所有新式類都從object
繼承並且是type
的實例。在Python 2系列2.2以上,二種類都可以使用[51]。在Python 3.0中淘汰了舊式類。
長期規劃是支援漸進類型[124],並且自從Python 3.5,語言的語法允許指定靜態型別,但在預設實現CPython中不檢查它們。有實驗的叫做「mypy」的可選的靜態型別檢查器支援編譯期型別檢查[125]。
類型 | 可變性 | 描述 | 語法例子 |
---|---|---|---|
bool
|
不可變 | 布林值 | True False
|
int
|
不可變 | 理論上無限制大小的整數[126] | 42
|
float
|
不可變 | 雙精度浮點數。精度是機器依賴的但實際上一般實現為64位元IEEE 754數而帶有53位的精度[127] |
|
complex
|
不可變 | 複數,具有實部和虛部 | 3+2.7j
|
range
|
不可變 | 通常用在迴圈中的數的序列,規定在for 迴圈中的次數[128]
|
range(1, 10) range(10, -5, -2)
|
str
|
不可變 | 字串,Unicode程式碼點序列 | 'Wikipedia' "Wikipedia" """Spanning
multiple
lines"""
|
bytes
|
不可變 | 位元組序列 | b'Some ASCII' b"Some ASCII" bytes([119, 105, 107, 105])
|
bytearray
|
可變 | 位元組序列 | bytearray(b'Some ASCII') bytearray(b"Some ASCII") bytearray([119, 105, 107, 105])
|
list
|
可變 | 列表,可以包含混合的類型 | [4.0, 'string', True] []
|
tuple
|
不可變 | 元組,可以包含混合的類型 | (4.0, 'string', True) ('single element',) ()
|
dict
|
可變 | 鍵-值對的關聯陣列(或稱字典);可以包含混合的類型(鍵和值),鍵必須是可雜湊的類型 | {'key1': 1.0, 3: False} {}
|
set
|
可變 | 無序集合,不包含重複項;可以包含混合的類型,如果可雜湊的話 | {4.0, 'string', True} set()
|
frozenset
|
不可變 | 無序集合,不包含重複項;可以包含混合的類型,如果可雜湊的話 | frozenset([4.0, 'string', True])
|
types.EllipsisType
|
不可變 | 省略號預留位置,用作NumPy陣列的索引 | ... Ellipsis
|
types.NoneType
|
不可變 | 表示值缺席的物件,在其他語言中經常叫做null | None
|
types.NotImplementedType
|
不可變 | 可從多載運算子返回的預留位置,用來指示未支援的運算數(operand)類型 | NotImplemented
|
除了各種資料類型,Python直譯器內建了還有很多其他類型,比如上下文管理器類型,模組、方法、程式碼物件、類型物件、內部物件等類型。
數學[編輯]
Python的算術運算使用平常的符號+
、-
、*
、/
,下取整除法算符//
和模除%
(這裡的餘數可以是負數,比如4 % -3 == -2
)。它還有指數算符**
,比如5**3 == 125
及9**0.5 == 3.0
,和矩陣乘法算符@
[101]。這些算符就像在傳統數學中一樣運算,具有同樣的優先級規則,中綴算符+
、-
還可以分別表示取原數和取相反數的一元算符。
在整數之間的除法/
產生浮點數結果。除法/
的表現隨著版本不同而有著顯著變化[129]。
Python提供了round()
函式用於把一個浮點數修約成最近的整數[130]。
Python允許由比較運算連結起來的布林表達式表現得如在數學中常用的一樣。比如,表達式a < b < c
測試a
小於b
並且b
小於c
[131]。C衍生語言不一樣的直譯這個表達式:在C中,這個表達式將首先求值a < b
,結果為0
或1
,接著把這個結果比較於c
[132]。
Python對所有整數運算使用任意精度算術。在decimal
模組中的Decimal
類型/類提供十進位浮點數到預定義的任意精度並有多種修約模式[133]。在fractions
模組中的Fraction
類提供任意精度的有理數[134]。
由於Python有著廣泛的數學庫,除了求絕對值函式abs()
列入內建函式之外,大多數數學函式處於math
和cmath
模組內。前者用於實數運算,而後者用於複數運算。[aj]特別是,第三方庫NumPy進一步擴充了原生能力,Python經常被用作科學手稿語言來處理如數值資料處理和操縱等問題[135][136]。
標準庫[編輯]
Python擁有一個強大的標準庫[137]。Python語言的核心只包含數值、字串、列表、字典、檔案等常見類型和函式,而由Python標準庫提供了系統管理、網路通信、文字處理、資料庫介面、圖形系統、XML處理等額外的功能。
Python標準庫的主要功能有:
- 文字處理,包含文字格式化、正規表示式、文字差異計算與合併、Unicode支援,二進位資料處理等功能。
- 檔案系統功能,包含檔案和目錄操作、建立臨時檔案、檔案壓縮與歸檔、操作設定檔等功能。
- 作業系統功能,包含執行緒與行程支援、IO復用、日期與時間處理、呼叫系統函式、紀錄檔(logging)等功能。
- 網路通信,包含網路通訊端,SSL加密通信、非同步網路通信等功能。支援HTTP,FTP,SMTP,POP,IMAP,NNTP,XMLRPC等多種網路協定,並提供了編寫網路伺服器的框架。
- W3C格式支援,包含HTML,SGML,XML的處理。
- 其它功能,包括國際化支援、數學運算、HASH、Tkinter等。
程式碼實例[編輯]
一個在標準輸出裝置上輸出Hello World的簡單程式,這種程式通常作為開始學習程式語言時的第一個程式,可將如下程式碼錄入純文字檔案並隨意命名比如program01.py
,然後執行這個程式python3 program01.py
:
print("Hello, world!")
Python也可以單步直譯執行。執行Python直譯器進入互動式命令列的環境,你可以在提示符號>>>
旁輸入print("Hello, world!")
,按Enter鍵輸出結果:
>>> print('Hello, world!')
Hello, world!
計算正數的階乘的程式碼:
n = int(input('键入一个数,就会打印它的阶乘: '))
if n < 0:
raise ValueError('错误,输入不正确!请输入一个非负数')
fact = 1
for i in range(2, n + 1):
fact *= i
print(fact)
注意,在Python 3.0及以上版本中,print
是個函式,需要在要列印的字串前後加上圓括號;在Python 2.6以下版本中,print
是一個關鍵字和命令而不加圓括號。
實現[編輯]
Python是一門跨平台的手稿語言,Python規定了一個Python語法規則,根據該規則可編寫Python直譯器[138]。Python屬於動態語言,將Python程式編譯成中間形式的位元組碼[139],並接著在它的虛擬機器上執行[140],相較於C/C++等編譯成機器碼的編譯語言而言執行速度較慢[141]。
- 活躍開發的實現
- CPython:官方的直譯器,需要區別於其他直譯器的時候才以CPython稱呼。
- MicroPython和CircuitPython:它們是為微控制器而最佳化的Python 3變體。
- Pyston:CPython 3.8.12的分叉,具有包括JIT的額外效能最佳化[142]。Pyston還將其JIT部份作為擴充模組pyston_lite_autoload來單獨發行,它支援Python3.7—3.10[143]。
- Cinder:由Meta開源釋出,它是Meta內部使用的面向效能的CPython 3.10分叉,具有包括JIT的很多最佳化[144]。
- PyPy:用RPython書寫的Python實現,其主線版本相容至CPython 3.8,測試版本相容至CPython 3.9,它採用了跟蹤JIT,預設支援stackless模態。
- Stackless Python:實現微執行緒的CPython 3.8分叉,它不使用C記憶體堆疊,因而允許大規模並行程式。
- 到其他語言的交叉編譯器
- Cython:將擴充了靜態型別的Python超集編譯成C或C++。
- Numba:使用LLVM,將包括很多NumPy函式的聚焦數值計算的Python子集,翻譯成快速的機器碼,它為在CPU和GPU上並列化Python程式碼提供了大量選項。
- Pyjion:CPython的JIT擴充,它將Python程式碼編譯成本機CIL,從而使用.NET 7的CoreCLR來執行它[145]。
- Nuitka:用Python書寫的到C11或C++03的最佳化編譯器,它能建立不需單獨的安裝器就能執行的可執行程式[146]。
- Pythran:將聚焦於科學計算的Python子集編譯成C++11的提前編譯器,它能利用上多核和SIMD指令單元[147]。
- MyHDL:將Python編譯成VHDL。
仍在維護中的舊版本實現有:IronPython,它是面向.NET和Ecma CLI的Python 2.7實現,它還有處在開發狀態的3.4版本實現;Jython,它是用Java實現的Python 2.7。
開發環境[編輯]
通用文字編輯器[編輯]
很多並非整合式開發環境軟體的文字編輯器,也對Python有不同程度的支援,並且加上專門為Python設計的編輯器外掛程式也會有很高的可用性。
專用開發環境[編輯]
適用於Python的整合式開發環境(IDE)軟體,除了標準二進位釋出包所附的IDLE之外,還有許多其他選擇。其中有些軟體設計有語法著色、語法檢查、執行偵錯、自動補全、智慧型感知等便利功能。由於Python的跨平台出身,這些軟體往往也具備各種作業系統的版本或一定的移植性。
- IDLE:Python「標準」IDE,一般隨Python而安裝,支援較少的編輯功能,偵錯功能也比較弱。
- Eric:基於PyQt的自由的IDE,支援自動補全、智慧型感知、自動語法檢查、工程管理、svn/mercurial整合、自動單元測試等功能,具有可延伸的外掛程式系統,通過可選外掛程式支援Git整合。偵錯功能與Visual Studio和Eclipse類似。
- Spyder:開源的跨平台科學計算IDE。
- PyScripter:功能較全的開源IDE,使用Delphi開發。
- PyCharm:由JetBrains公司出品,具備一般IDE的功能,比如偵錯、語法突顯、Project管理、程式碼跳轉、智慧型提示、自動完成、單元測試、版本控制等等,另外,它還提供了一些功能用於Django開發,同時支援Google App Engine,還支援IronPython。它是商業軟體,但也具有社群版和教育版。
- Komodo和Komodo Edit:後者是前者的免費精簡版。
- WingIDE:商業軟體,有免費的功能有限的Wing IDE 101,適用於入門者教學。
應用[編輯]
在很多作業系統裡,Python是標準的系統元件。大多數Linux發行版和macOS都整合了Python,可以在終端機下直接執行Python。雖然Python可被粗略地分類為手稿語言,Python的支持者較喜歡稱它為一種高階動態語言,常像「膠水」一樣被用來連接軟體組件,已經顯著的區別於Unix shell、Windows PowerShell這樣的語言。基於Python的xonsh,是跨平台的、青睞Unix的shell語言和命令列介面[148]。
Python社群提供了大量的功能覆蓋眾多領域的第三方模組,其使用方式與標準庫類似。第三方模組可以使用Python/Cython或者C編寫。軟體工具SWIG和SIP,通過定義介面檔案或規定檔案的方式,可以將C/C++編寫的程式庫包裝為Python模組。Python直譯器本身也可以被整合到其它需要手稿語言的程式內。
pip是事實標準和官網推薦的用Python書寫的軟體套件管理系統[149],它通常連接到叫做Python包索引的一個公開軟體套件線上倉庫。pipenv自動為使用者專案建立和管理虛擬環境,還在安裝/卸裝軟體套件的時候,向Pipfile檔案增加/移除這個軟體套件[150]。pyenv可以安裝並輕易切換多個版本的Python[151]。
自從2003年,Python始終排行於TIOBE程式社群索引前十最流行程式語言,在2021年10月它首次達到了第一名最流行語言(居於C和Java之前)[152],並被選為2007年、2010年、2018年、2020年和2021年的年度程式語言[152]。
網路服務[編輯]
Python定義了WSGI標準應用介面來協調Http伺服器與基於Python的Web程式之間的溝通。比如,通過mod_wsgi模組,Apache可以運行用Python編寫的Web程式。Zope是著名的用Python編寫的開源的Web應用伺服器。Tornado是用Python語言寫成的非阻塞式web伺服器,也是輕量級的Web框架。
Python對於各種網路協定的支援很完善,因此經常被用於編寫伺服器軟體、網路爬蟲等Web開發。用Python編寫的一些Web框架,可以讓程式設計師輕鬆地開發和管理複雜的Web程式。著名的第三方Web框架和函式庫:
- Django:MTV架構[153]的Web開發框架,注重組件的重用性和「可插拔性」、快速開發和DRY法則。
- web2py:MVC架構的全棧Web框架,聚焦於快速開發,偏好約定優於組態方式。
- TurboGears:MVC架構的混合Web框架,可以擔任全棧框架或微框架二者。
- Pyramid:極簡主義的Web框架,不預定持久化方式,它是Pylons計劃的一部分。
- Flask:微Web框架,不要求特定的工具或庫。
- aiohttp:輕量級的Web框架[154],採用的是Python3的asyncio非同步特性。
- Twisted:事件驅動的網路程式框架。它支援多數標準的網路協定(包含客戶端和伺服器),並且提供了多種工具,被廣泛用於編寫高效能的伺服器軟體。
- Requests:適合於常人使用的HTTP庫,封裝了許多繁瑣的HTTP功能,極大地簡化了HTTP請求所需要的程式碼量。
- Beautiful Soup:用來解析HTML/XML的一個簡單易用Python包。
- gevent:是基於協程的高效能並行網路程式庫[155],使用greenlet在libev或libuv之上提供了高層的同步式API。
圖形化使用者介面[編輯]
Python本身包含了Tkinter庫,它是Python的業界標準GUI並被整合進入了IDLE。Tkinter基於了Tcl命令工具,能夠支援簡單的GUI開發。但是越來越多的Python程式設計師選擇第三方GUI套件來開發跨平台的桌面軟體,使用它們開發的桌面軟體執行速度快,與使用者的桌面環境相契合。著名的第三方GUI庫:
- PyQt:Qt的Python繫結庫,由Riverbank Computing公司自從1998年發行,採用GPL授權條款或商業授權條款。
- PySide:Qt的Python繫結庫,由Qt公司自從2009年發行,採用LGPL授權條款。
- PyGObject:替代了PyGTK,為Python程式存取基於GObject的庫提供了包裝庫,GObject是GTK、GIO和GStreamer等庫使用的物件系統。
- Kivy:用於開發多點觸控應用軟體的開源Python庫,採用了自然使用者介面(NUI)。
- WxPython:GUI程式框架wxWidgets的Python包裝庫,它與MFC的架構相似。
- PySimpleGUI:將Tkinter、Qt、WxPython和Remi[156]的GUI框架變換成簡單的介面[157]。
- Gooey:將幾乎所有Python 3控制台程式用一行程式碼轉變成GUI應用[158]。
- Pyforms:開發能夠在三種不同環境即桌面GUI、終端和網頁下執行的程式的Python框架[159]。
資料科學[編輯]
重要的資料科學用第三方軟體庫有:
- NumPy:Python的基礎性的科學計算軟體庫,提供了矩陣、線性代數、傅立葉變換等的解決方案。
- SciPy:用Python實現了MATLAB所有功能的軟體庫,使用NumPy的多維陣列作為基本資料結構。
- CuPy:NumPy/SciPy相容的GPU加速的陣列庫[160],它可在NVIDIA CUDA或AMD ROCm平台上充當其隨插即用替代者,來執行現存的NumPy/SciPy程式碼。
- pandas:用於資料分析和資料操縱的軟體庫,建造在NumPy基礎上,提供了類似於R語言中同名物件的加標籤資料結構「資料框」[161],和統計函式等。
- Dask:伸縮範圍從筆記型電腦至電腦叢集的平行計算庫[162],它由兩部份構成:為計算而最佳化的動態任務排程,和「大數據」搜集如並列的陣列、資料框和列表。這些搜集將常用介面如NumPy、pandas或Python迭代器,擴充到大過記憶體或分散式的環境,並列的搜集執行在動態任務排程器頂上。
- matplotlib:用於Python和NumPy的繪圖庫,實現類似MATLAB的繪圖功能。
- scikit-learn:基於NumPy、SciPy、Joblib[163]和threadpoolctl[164]的機器學習軟體庫,實現許多知名的機器學習演算法,其繪圖功能依賴於matplotlib。
- Dash:基於React、Flask和Plotly公司的Plotly.js[165]之上的框架,它將現代使用者介面元素如下拉選單、滑動條和圖形,直接連結至分析型Python程式碼[166]。它和Streamlit[167]、Panel[168]和Voilà[169],是被稱為「儀錶板」的資料視覺化工具[170]。
- PyMC:基於Theano的概率程式庫,用於貝葉斯統計建模和概率機器學習。
- TensorFlow:Google開發的一個端到端開源機器學習平台,它提供了Python API[171],其中實現了Keras API[172]。Keras現在是在TensorFlow 2上建立的深度學習高層API。SciKeras是對Keras模組的scikit-learn相容的包裝器[173]。
- PyTorch:Meta在Torch基礎上開發的開源的Python軟體套件,提供了具有強大的GPU加速的張量計算,和建立在基於tape的自動梯度系統上的深度神經網路。skorch是包裝了PyTorch的scikit-learn相容的神經網路庫[174]。
- JAX:Google開發的擁有可組合的函式變換的開源機器學習框架[175],結合了修改版本的針對NumPy的自動梯度庫Autograd[176],和TensorFlow中的加速線性代數庫XLA[177],它使用XLA來在GPU和TPU上編譯和執行NumPy程式。JAX除了用於開發新的人工神經網路軟體庫比如Flax[178],還用於概率程式庫比如NumPyro[179],和物理引擎比如Brax[180]。
- Ray:對人工智慧及Python應用的執行規模進行伸縮的統一框架[181]。它構成自一個核心的分散式執行時間系統,和加速機器學習工作負載的軟體庫工具箱(Ray AIR)。它支援TensorFlow或PyTorch,可整合於Dask、Apache Spark和Mars[182],可以部署在Kubernetes叢集和雲端VM之上。
其它種類的庫[編輯]
- SymPy:支援數學符號運算如微積分等的軟體庫,用於提供電腦代數系統。
- SQLAlchemy:針對關係型資料庫的物件關係對映(ORM)工具。
- Pillow:是基於Python的圖像處理庫[183],它支援廣泛的圖形檔案格式,分叉於已終止的PIL。
- PyOpenGL:到OpenGL 1.1-4.4和有關API的最常用跨平台Python繫結[184]。
- ModernGL:在OpenGL 3.3+核心上的Python包裝器[185],它簡化了簡單圖形應用如科學類比、遊戲和使用者介面的建立。
- VisPy:高效能互動式2D/3D資料視覺化庫[186],它通過OpenGL庫利用現代GPU的計算能力來顯示非常大的資料集。
- PyCUDA和PyOpenCL:不同於Nvidia儘可能匹配C API的cuda-python[187],PyCUDA提供對CUDA平行計算API的Python風格存取[188];PyOpenCL提供對OpenCL平行計算API的Python風格存取[189]。
- Kornia:基於PyTorch的可微分電腦視覺庫[190]。
- pygame:開發電動遊戲的Python軟體庫,基於了SDL庫[191]。
- pyglet:Python編寫的物件導向的遊戲和多媒體庫,利用了FFmpeg庫。
- pythonnet:針對.NET的程式包[192],它可以近乎無縫的整合.NET通用語言執行庫(CLR)。
- Fabric:經由SSH遠端執行shell命令的高層庫[193],它產生有用的Python物件作為回饋。
- Prefect:現代工作流程編排框架[194],它易於建造、排程和監視健壯的資料管線。
- PyInstaller:將Python應用和它的依賴項捆綁成一個單一的包[195],從而不需要安裝Python直譯器或任何模組就可以執行應用。
應用軟體[編輯]
有一些Linux發行版的安裝器使用Python語言編寫。在RPM系列Linux發行版中,有一些系統組件就是用Python編寫的。一些著名的網際網路公司在內部使用Python[144]。一些遊戲比如EVE,使用Python編寫遊戲的邏輯、伺服器。如下著名應用使用Python編寫或將它作為嵌入式指令碼:
- IPython:以多種程式語言進行互動式計算的命令shell和Jupyter的核心,最初為Python開發,它提供了內省、富媒體、shell語法、tab補全和歷史。
- Conda:跨平台的、語言無關的二進位包管理器,它被Anaconda發行採用。
- SCons:軟體建造工具,它可代替make構建編譯程式。
- Ubiquity:Ubuntu的安裝器。
- Anaconda:Red Hat Enterprise Linux和Fedora的安裝器。
- Portage:Gentoo Linux使用Python編寫的軟體包管理系統。
- Gunicorn:使用Python語言編寫的WSGI Web伺服器。
- Plone:基於Zope的內容管理系統。
- Mezzanine:基於Django框架的內容管理系統。
- Odoo:ERP軟體,有開源社群版。
- SageMath:覆蓋許多數學功能的應用軟體。
- Veusz:用Python、PyQt和NumPy寫成的科學繪圖軟體,可生成能夠出版的PDF或SVG輸出。
- LibreOffice:自從2013年的版本4.0開始,包含了Python並意圖用它來替代Java,它的Python指令碼提供器是核心特徵[196]。
- Blender:開源3D繪圖軟體,使用Python作為建模工具與GUI語言。
- Inkscape:開源的SVG向量圖形編輯器,使用Python用於外掛程式。
- Panda3D:開源遊戲引擎,包括了圖形、音訊、I/O、碰撞偵測和其他與3D遊戲有關的功能,使用Python作為遊戲開發語言[197]。
社群流行[編輯]
- PyCon:各地社群舉辦的會議,通常每年舉辦。各社群在會議中討論Python相關的議題。
- Python Discord:參與者眾多的Python社群[198]。
- PyLadies:由女性社群發起的社群,主要注重於發展Python的女性程式設計社群。
- Django Girls:使用Django網頁設計框架,推廣使用Python進行網頁設計的技術。
影響的語言[編輯]
Python的設計和哲學已經影響了很多其他程式語言:
- Boo:使用了縮排、類似的語法和類似的物件模型[199]。
- Cobra:使用了縮排和類似的語言,而且它的致謝文件將Python列為影響它的首要語言[200]。
- CoffeeScript:是交叉編譯至JavaScript的程式語言,有受Python啟發的語法。
- ECMAScript/JavaScript:從Python借鑑了迭代器和生成器[201]。
- GDScript:是非常類似Python的手稿語言,內建入了Godot遊戲引擎[202]。
- Genie:基於Vala編譯器的具有近似Python語法的一種語言。
- Go:設計為「有動態語言如Python的工作速度」[203],並共享了相同的分片陣列的語法。
- Groovy:受到Python等動態型別語言的影響[204]。
- Nim:使用縮排和類似的語法[205]。
- Swift:是Apple開發的程式語言,有受Python啟發的語法[206]。
Ruby的建立者松本行弘曾說過:「我想要一種手稿語言,比Perl更加強力而且比Python更加物件導向,因此我決定設計自己的語言」[207]。Julia設計原則中有一條是:「像Python一樣可用於通用程式」[28]。
程式碼範例[編輯]
- ^ 縮排範例:
def print_something(age): if age < 21: print("你不能買酒") #美國法律規定21歲以下的人不能購買酒 else: print("你能買酒") print("你能買口香糖") # 参数比后续部份多一层缩进 def long_function_name( var_one, var_two, var_three, var_four): # 可选的圆括号内后续行多一层缩进 if (this_is_first_thing and that_is_second_thing): do_something() # 可选的圆括号内后续行不额外缩进 elif (this_is_third_thing and that_is_fourth_thing): do_something_different() # 参数相对行首缩进一层 spam = long_function_name( arg_one, arg_two, arg_three, arg_four) # 参数按开括号界定垂直对齐 eggs = long_function_name(arg_one, arg_two, arg_three, arg_four) # 可选的闭括号位置 my_list = [ 1, 2, 3, 4, 5, 6, ] # 可选的闭括号位置 my_set = { 1, 2, 3, 4, 5, 6, }
- ^ 採用了並列賦值的斐波那契數列函式範例:
def fib(n): # 写出从第0项到第n项的Fibonacci系列 a, b, i = 0, 1, 0 while i <= n: print(a, end=' ') a, b, i = b, a+b, i+1 print()
- ^ 產生素數的惰性生成器的範例:
from itertools import count def generate_primes(stop_at=0): if stop_at != 1: primes = [2] yield 2 for n in count(3, 2): if 0 < stop_at < n: return # 引发StopIteration异常 composite = False for p in primes: if not n % p: composite = True break elif p ** 2 > n: break if not composite: primes.append(n) yield n
上述函式的隱式迭代用例:
for i in generate_primes(): # 迭代于100以内所有素数上 if i > 100: break print(i)
在生成器表達式中使用上述函式,定義了一個惰性的、巨大而並非無限的搜集的範例:
from itertools import islice primes_under_million = (i for i in generate_primes() if i < 1000000) two_thousandth_prime = islice(primes_under_million, 1999, 2000) print(next(two_thousandth_prime))
- ^ 遵循EAFP風格的例外處理範例:
f = None try: f = open("aFileName", mode="w") f.write(could_make_error()) # 不存在could_make_error()则产生错误 except IOError as error: print(error) print("不能打开文件") except: # 捕获所有异常 print("未预期的错误") else: # 在没有出现异常时执行 print("文件写入完全成功") finally: # 清除行动,总是执行 if f: f.close()
- ^ 使用
with
將檔案作為資源來管理的範例:from contextlib import contextmanager @contextmanager def opened(filename, mode="r"): try: f = open(filename, mode) except IOError as error: print(error) yield None else: try: yield f finally: f.close() with opened("aFileName", mode="w") as f: try: f.write(could_make_error()) # 不存在could_make_error()则产生错误 except AttributeError: print("不能打开文件") except: # 捕获所有异常 print("未预期的错误") else: # 在没有出现异常时执行 print("文件写入完全成功")
- ^ 用生成器類比協程範例:
def produce(n): try: for item in range(n): print('producing item {} ->'.format(item)) yield item except GeneratorExit: return def consume(): item = None try: while True: item = yield item print('consuming item {} <-'.format(item)) except GeneratorExit: return t1 = produce(10) t2 = consume() next(t2) try: while True: a = t1.send(None) b = t2.send(a) except StopIteration: pass
- ^ 原生的協程範例:
import asyncio import random async def produce(queue, n): for item in range(n): # 生产一个项目,使用sleep模拟I/O操作 print('producing item {} ->'.format(item)) await asyncio.sleep(random.random()) # 将项目放入队列 await queue.put(item) # 指示生产完毕 await queue.put(None) async def consume(queue): while True: # 等待来自生产者的项目 item = await queue.get() if item is None: break # 消费这个项目,使用sleep模拟I/O操作 print('consuming item {} <-'.format(item)) await asyncio.sleep(random.random()) async def main(): queue = asyncio.Queue() task1 = asyncio.create_task(produce(queue, 10)) task2 = asyncio.create_task(consume(queue)) await task1 await task2 asyncio.run(main())
- ^ 列表的推導式範例。比如:
>>> [x + 3 for x in range(4)] [3, 4, 5, 6]
快速排序演算法可以優雅的(儘管不高效的)使用列表推導式表達為:
def qsort(L): if L == []: return [] pivot = L[0] return (qsort([x for x in L[1:] if x < pivot]) + [pivot] + qsort([x for x in L[1:] if x >= pivot]))
- ^ 生成器表達式範例。比如:
>>> sum(x * x for x in range(10)) 285 >>> dict((n, n*n) for n in range(5)) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} >>> set(n*n for n in range(5)) {0, 1, 4, 9, 16}
- ^ 字典推導式
{expr1: expr2 for k, v in d}
,等價於:result={} for k, v in d.items(): result[expr1]=expr2 return result
>>> {x: x + 3 for x in range(4)} {0: 3, 1: 4, 2: 5, 3: 6}
集合推導式
{expr1 for x in stuff}
,等價於:result = set() for x in stuff: result.add(expr1) return result
>>> {x + 3 for x in range(4)} {3, 4, 5, 6}
- ^ 匿名函式範例:
>>> from functools import reduce >>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 15 >>> fac = lambda n: (1 if n<2 else n*fac(n-1)) >>> fac(5) 120 >>> [*map(fac, [1, 2, 3, 4, 5])] [1, 2, 6, 24, 120]
不動點組合子範例:
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) >>> Y(fac)(5) 120 >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) >>> Y(fib)(6) 8 >>> [*map((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))))(lambda f: lambda n: (1 if n<2 else n*f(n-1))), [1, 2, 3, 4, 5])] [1, 2, 6, 24, 120]
上述Y組合子程式碼源出自Rosetta Code. [2020-10-21]. (原始內容存檔於2021-01-11).其原理可參見Equational derivations of the Y combinator and Church encodings in Python. [2020-10-21]. (原始內容存檔於2020-11-12).
- ^ 序列解包、可迭代解包和字典解包範例:
>>> a = [1, 2, 3]; b = [4, 5] >>> i, j, k = a >>> print(i, j, k) 1 2 3 >>> c = [*a, b] >>> c [1, 2, 3, [4, 5]] >>> d = {*a, *b} >>> d {1, 2, 3, 4, 5} >>> e = (*a, *b) >>> e (1, 2, 3, 4, 5) >>> f = {"as":1, "bs":2 }; g = {"cs":3, "ds":4} >>> h = {**f, **g} >>> h {'as': 1, 'bs': 2, 'cs': 3, 'ds': 4}
- ^ 格式化字串的範例,例如下列命令列
echo
命令:num="3"; printer="HP Laserjet" echo "I just printed ${num} pages to the printer ${printer}"
等價於如下Python中的任何一種
print
函式呼叫:num = 3; printer="HP Laserjet" print(f"I just printed {num} pages to the printer {printer}") print("I just printed {} pages to the printer {}".format(num, printer)) print("I just printed {0} pages to the printer {1}".format(num, printer)) print("I just printed {num} pages to the printer {printer}".format(num=num, printer=printer)) print("I just printed %s pages to the printer %s" % (num, printer)) print("I just printed %(num)s pages to the printer %(printer)s" % {"num": num, "printer": printer})
- ^ 多行字串文字帶有字串插值(使用了
format
方法)的範例:print("""亲爱的{recipient}, 我希望你离开Sunnydale并永不返回. 不是很爱你的, {sender} """.format(sender="吸血鬼猎人Buffy", recipient="Spike"))
- ^ 原始字串的範例:
>>> # Windows路径,即使是原始字符串也不能结束于反斜杠 >>> r"C:\Spam\Eggs\Ham\" File "<stdin>", line 1 r"C:\Spam\Eggs\Ham\" ^ SyntaxError: EOL while scanning string literal >>> dos_path = r"C:\Spam\Eggs\Ham\ " # 通过增加尾随的空格 >>> dos_path.rstrip() # 并接着移除它来避免错误 'C:\\Spam\\Eggs\\Ham\\' >>> quoted_dos_path = r'"{}"'.format(dos_path) >>> quoted_dos_path '"C:\\Spam\\Eggs\\Ham\\ "' >>> # 匹配具有可能的反斜杠引用的引用字符串的正则表达式 >>> import re >>> re.match(r'"(([^"\\]|\\.)*)"', quoted_dos_path).group(1).rstrip() 'C:\\Spam\\Eggs\\Ham\\' >>> code = 'spam(2, eggs)' >>> # 反转有二个参数的函数调用的两个实际参数 >>> re.sub(r'\(([^,]*),\s*([^,]*)\)', r'(\2, \1)', code) 'spam(eggs, 2)' >>> # 注意如果实际参数中有圆括号或逗号则上例无效。
- ^ 字串文字串接範例:
>>> title = "SICP in Python"" - " \ ... 'CS61A: Online Textbook'
等價於:
>>> title = "SICP in Python - CS61A: Online Textbook"
- ^ 下面幾個判斷語句為真,表示列表分片結果符合預期:
>>> nums = [1, 3, 5, 7, 8, 13, 20] >>> nums[2:5] == [5, 7, 8] #从下标为2的元素切割到下标为5的元素,但不包含下标为5的元素。 True >>> nums[1:] == [3, 5, 7, 8, 13, 20] #切割到最后一个元素。 True >>> nums[:-3] == [1, 3, 5, 7] #从最开始的元素一直切割到倒数第3个元素。 True >>> nums[:] == [1, 3, 5, 7, 8, 13, 20] #返回所有元素。改变新的列表不会影响到nums。 True >>> nums[1:5:2] == [3, 7] #从下标为1的元素切割到下标为5的元素,但不包含下标为5的元素,且步长为2。 True
- ^ 詞法閉包的例子:
def f(x): def g(y): return x + y return g # 返回一个闭包。 h = lambda x: lambda y: x + y # 将指定闭包赋值给变量。 a = f(1) b = h(1) c = f(2) # 使用存储在变量中的闭包。 assert a(5) == 6 assert b(5) == 6 assert c(5) == 7 # 使用闭包而不事先把它们绑定到变量。 assert f(1)(5) == 6 # f(1)是个闭包。 assert h(1)(5) == 6 # h(1)是个闭包。 assert f(2)(5) == 7 # f(2)是个闭包。
- ^ 函式的形實參數二者結合範例。例如:
>>> def spam(a): ... a.append('LovelySpam') ... >>> def eggs(b): ... b=100 #实际上是重新绑定了另一个整型对象100 ... >>> a=[] >>> b=10 >>> spam(a) >>> eggs(b) >>> print(a) ['LovelySpam'] >>> print(b) 10
- ^ 局部變數和全域變數範例:
>>> def spam(): ... print(b) ... >>> b=10 >>> spam() 10 >>> def spam(): ... print(b) ... b=100 ... >>> b=10 >>> spam() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in spam UnboundLocalError: local variable 'b' referenced before assignment >>> def spam(): ... print(b) ... global b ... b=100 ... File "<stdin>", line 3 SyntaxError: name 'b' is used prior to global declaration >>> def spam(): ... global b ... print(b) ... b=100 ... >>> b=10 >>> spam() 10 >>> b 100
- ^ 非局部變數範例:
>>> def spam(): ... def eggs(): ... global b ... print(b) ... b=1000 ... b=100 # 对eggs()而言是非局部变量 ... eggs() ... >>> b=10 >>> spam() 10 >>> b 1000 >>> def spam(): ... def eggs(): ... nonlocal b ... b=1000 ... b=100 # 对eggs()而言是非局部变量 ... eggs() ... print(b) ... >>> b=10 >>> spam() 1000 >>> b 10
- ^ 函式的形式參數預設值的永續性範例:
>>> def f(a, L=[]): ... L.append(a) ... return L ... >>> print(f(1)) [1] >>> print(f(2)) [1, 2] >>> print(f(3)) [1, 2, 3]
- ^ 函式的形式參數預設值的定義範例:
>>> from inspect import getfullargspec >>> def func(p1, /, p2, p3="x", *, p4): pass ... >>> getfullargspec(func) FullArgSpec(args=['p1', 'p2', 'p3'], varargs=None, varkw=None, defaults=('x',), kwonlyargs=['p4'], kwonlydefaults=None, annotations={})
- ^ 函式的可變參數的定義範例:
>>> from inspect import getfullargspec >>> def func(p1, /, p2, *args, p3, **kwargs): pass ... >>> getfullargspec(func) FullArgSpec(args=['p1', 'p2'], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=['p3'], kwonlydefaults=None, annotations={})
- ^ 定義修飾器的範例:
def viking_chorus(myfunc): def inner_func(*args, **kwargs): for i in range(3): myfunc(*args, **kwargs) return inner_func
呼叫修飾器的範例:
@viking_chorus def menu_item(*args): print(", ".join(args)+", and spam")
等價於:
def menu_item(*args): print(", ".join(args)+", and spam") menu_item = viking_chorus(menu_item)
viking_chorus
修飾後的menu_item
將原來定義執行3次:>>> menu_item("egg","bacon") egg, bacon, and spam egg, bacon, and spam egg, bacon, and spam
- ^ 修飾器工廠範例,這裡的
favourite_colour
接受一個實際參數,並返回一個修飾器:def favourite_colour(colour): def decorator(func): def wrapper(*args, **kwargs): print(f"My favourite colour is {colour}.") func(*args, **kwargs) return wrapper return decorator def invincible(func): def wrapper(*args, **kwargs): print("I'm invincible!") func(*args, **kwargs) return wrapper
使用毗連的修飾詞連結修飾器範例:
@invincible @favourite_colour("blue") def black_knight(): print("None shall pass.")
使用中間變數連結修飾器範例:
blue_decorator = favourite_colour("blue") decorated_by_blue = blue_decorator(black_knight) black_knight = invincible(decorated_by_blue)
它們等價於:
black_knight = invincible(favourite_colour("blue")(black_knight))
black_knight()結果為:
>>> black_knight() I'm invincible! My favourite colour is blue. None shall pass.
- ^ 呼叫函式使用幫助資訊範例。比如:
>>> def randint(a, b): ... "Return random integer in range [a, b], including both end points." ... >>> help(randint) Help on function randint in module __main__: randint(a, b) Return random integer in range [a, b], including both end points.
- ^ 如下這樣給參數增加類型標註的提示資訊:
def send_mail(from: str, to: str, title: str, body: str) -> bool: pass
- ^ 物件的方法範例:
>>> class Fish(object): ... hungry = True ... def eat(self, food): ... if food is not None: ... self.hungry=False ... >>> def status(self): ... print("Hungray!" if self.hungry else "Not hungray!") ... >>> e = Fish() >>> status(e) Hungray! >>> Fish.hungry = False >>> from types import MethodType >>> e.status = MethodType(status, e) >>> e.status() Not hungray! >>> Fish.hungry = True >>> Fish.status = status >>> f = Fish() >>> Fish.status(f) Hungray! >>> f.eat("earthworm") >>> f.status() Not hungray!
- ^ 特殊方法和子類呼叫超類別方法的例子:
>>> class Thought(object): ... cls_name = "类型Thought" ... def __init_subclass__(cls): ... cls.cls_name = "类型Thought的子类型" ... def __init__(self, *args, **kwargs): ... print(f"我是{type(self).cls_name}的新对象!") ... if len(args) != 0 or len(kwargs) !=0: ... print(f"init: nargs={len(args)}, nkwargs={len(kwargs)}") ... self.notion = "我觉得我在平行宇宙中把车停歪了." ... def message(self, *args): ... print(self.notion) ... if len(args) != 0: ... print("\n".join(args)) ... >>> class Advice(Thought): ... def message(self): ... super(Advice, self).message("警告: 日历里的日期比它们看起来更近!") ... >>> t = Thought() 我是类型Thought的新对象! >>> t.message() 我觉得我在平行宇宙中把车停歪了. >>> a = Advice() 我是类型Thought的子类型的新对象! >>> a.message() 我觉得我在平行宇宙中把车停歪了. 警告: 日历里的日期比它们看起来更近! >>> # 内省一下: >>> [*super.__dict__] ['__repr__', '__getattribute__', '__get__', '__init__', '__new__', '__thisclass__', '__self__', '__self_class__', '__doc__'] >>> [*super(Advice).__thisclass__.__dict__] ['__module__', 'message', '__doc__', 'cls_name'] >>> super(Advice).__thisclass__.__dict__['cls_name'] '类型Thought的子类型' >>> [*super(Advice, a).__self__.__dict__] ['notion'] >>> super(Advice, a).__self_class__.__dict__['cls_name'] '类型Thought的子类型' >>> super(Advice, a).message() 我觉得我在平行宇宙中把车停歪了. >>> super(Advice).__get__(a).message() 我觉得我在平行宇宙中把车停歪了.
- ^ 特殊方法、類別方法和靜態方法(
__new__()
)範例:>>> from weakref import WeakValueDictionary >>> class D: ... _template = {} ... _obj_dict = WeakValueDictionary() ... def __new__(cls, *args, **kwargs): ... obj = super(D, cls).__new__(cls) ... cls._obj_dict[id(obj)] = obj ... return obj ... @classmethod ... def load(cls, dict): ... cls._template.update(dict) ... @classmethod ... def create(cls, *args, **kwargs): ... return cls(cls._template, *args, **kwargs) ... @classmethod ... def count(cls): ... return len(cls._obj_dict) ... def __init__(self, dict={}, /, *args, **kwargs): ... self.__dict__.update(dict) ... self.__dict__.update(kwargs) ... def __call__(self, *args, **kwargs): ... self.__dict__.update(kwargs) ... return self.__dict__.copy() ... def __len__(self): ... return len(self.__dict__) ... def __getitem__(self, key): ... return self.__dict__[key] ... def __setitem__(self, key, value): ... self.__dict__[key] = value ... >>> a = {"ak": 1, "bk": 2, "ck": 3} >>> d = D(a, dk=4) >>> d() {'ak': 1, 'bk': 2, 'ck': 3, 'dk': 4} >>> D.load(a) >>> e = D.create(ck=4) >>> e() {'ak': 1, 'bk': 2, 'ck': 4} >>> f = D(ak=1, bk=2) >>> f(ck=3) {'ak': 1, 'bk': 2, 'ck': 3} >>> f['ak'] 1 >>> f['ak'] = 5 >>> f() {'ak': 5, 'bk': 2, 'ck': 3} >>> len(f) 3 >>> D.count() 3 >>> del f >>> D.count() 2 >>> d.__weakref__ in D._obj_dict.valuerefs() True
- ^ 在類中採用資料描述器的範例:
>>> class RevealAccess: ... """正常的设置和返回值的数据描述器, ... 它还打印记录这次访问的一个消息。 ... """ ... def __init__(self, initval=None, name='var'): ... self.val = initval ... self.name = name ... def __get__(self, obj, objtype): ... print('Retrieving', self.name) ... return self.val ... def __set__(self, obj, val): ... print('Updating', self.name) ... self.val = val ... >>> class MyClass: ... x = RevealAccess(10, 'var "x"') ... y = 5 ... >>> m = MyClass() >>> m.x Retrieving var "x" 10 >>> vars(m) {} >>> MyClass.__dict__['x'].val 10 >>> m.x = 20 Updating var "x" >>> vars(m) {} >>> MyClass.__dict__['x'].val 20 >>> m.y 5 >>> vars(m) {} >>> m.y = 5 >>> vars(m) {'y': 5}
- ^ 在類中呼叫
property()
的例子:>>> class C: ... def __init__(self): ... self.__x = None ... def getx(self): ... return self.__x ... def setx(self, value): ... self.__x = value ... def delx(self): ... del self.__x ... x = property(getx, setx, delx, "I'm the 'x' property.") ... >>> c = C() >>> vars(c) {'_C__x': None} >>> {*C.__dict__} {'__init__', 'setx', '__weakref__', 'delx', 'x', 'getx', '__doc__', '__module__', '__dict__'}
上述程式碼可以採用修飾詞進一步的書寫為:
>>> class C: ... def __init__(self): ... self.__x = None ... @property ... def x(self): ... """I'm the 'x' property.""" ... return self.__x ... @x.setter ... def x(self, value): ... self.__x = value ... @x.deleter ... def x(self): ... del self.__x ... >>> c = C() >>> vars(c) {'_C__x': None} >>> {*C.__dict__} {'__init__', '__weakref__', 'x', '__doc__', '__module__', '__dict__'}
- ^
建立列表的特殊語法範例:
a_list = [1, 2, 3, "a dog"]
採用正常的物件建立方式的範例:
a_second_list = list() a_second_list.append(4) a_second_list.append(5)
建立元組的特殊語法範例:
a_tuple = 1, 2, 3, "four"
建立集合的特殊語法範例:
some_set = {0, (), False}
建立字典的特殊語法範例:
a_dictionary = {"key 1": "value 1", 2: 3, 4: []}
- ^
兩個類及元類等的實例關係(藍色連接)與繼承關係(綠色連接)示意圖:
r = object c = type class M(c): pass class A(metaclass=M): pass class B(A): pass b = B()
>>> type(b) <class '__main__.B'> >>> print(type(B), B.__bases__) <class '__main__.M'> (<class '__main__.A'>,) >>> print(type(A), A.__bases__) <class '__main__.M'> (<class 'object'>,) >>> print(type(M), M.__bases__) <class 'type'> (<class 'type'>,) >>> print(type(c), c.__bases__) <class 'type'> (<class 'object'>,) >>> print(type(r), r.__bases__) <class 'type'> ()
- ^ 數學運算範例。比如:
>>> def mean(seq): ... return sum(seq) / len(seq) ... >>> mean([3, 4]) 3.5 >>> import math >>> print(math.sin(math.pi/2)) 1.0
註釋[編輯]
- ^ Guttag, John V. Introduction to Computation and Programming Using Python: With Application to Understanding Data. MIT Press. 12 August 2016. ISBN 978-0-262-52962-4.
- ^ 2.0 2.1 Python 3.11.1, 3.10.9, 3.9.16, 3.8.16, 3.7.16, and 3.12.0 alpha 3 are now available. 2022年12月6日 [2022年12月7日] (英語).
- ^ 3.0 3.1 Python 3.12.0 alpha 4 released. 2023年1月10日 [2023年1月11日] (英語).
- ^ "Python 3.12 Alpha 4 Released For Testing"; 宣傳物: Phoronix; 作品或名稱的語言: 英語; 出版日期: 2023年1月11日; 檢索日期: 2023年1月11日.
- ^ Why is Python a dynamic language and also a strongly typed language - Python Wiki. wiki.python.org. [2021-01-27]. (原始內容存檔於2021-03-14).
- ^ PEP 483 -- The Theory of Type Hints. Python.org. [2020-04-22]. (原始內容存檔於2020-06-14).
- ^ File extension .pyo was removed in Python 3.5. See PEP 0488 (頁面存檔備份,存於網際網路檔案館)
- ^ Holth, Moore. PEP 0441 -- Improving Python ZIP Application Support. 2014-03-30 [2015-11-12]. (原始內容存檔於2018-12-26).
- ^ 存档副本. [2022-08-26]. (原始內容存檔於2023-01-21).
- ^ RustPython. [2022-03-04]. (原始內容存檔於2022-04-24).
- ^ Starlark Language. [25 May 2019]. (原始內容存檔於2020-06-15).
- ^ 12.0 12.1 12.2 Why was Python created in the first place?. Python FAQ. [2007-03-22]. (原始內容存檔於2008-02-23).
- ^ Ada 83 Reference Manual (raise statement). [2021-03-14]. (原始內容存檔於2019-10-22).
- ^ Kuchling, Andrew M. Interview with Guido van Rossum (July 1998). amk.ca. 22 December 2006 [12 March 2012]. (原始內容存檔於1 May 2007).
- ^ 15.0 15.1 itertools — Functions creating iterators for efficient looping — Python 3.7.1 documentation. docs.python.org. [2020-04-22]. (原始內容存檔於2020-06-14).
- ^ van Rossum, Guido. An Introduction to Python for UNIX/C Programmers. Proceedings of the NLUUG Najaarsconferentie (Dutch UNIX Users Group). 1993 [2021-03-14]. (原始內容存檔於2013-06-17).
even though the design of C is far from ideal, its influence on Python is considerable.
- ^ 17.0 17.1 Classes. The Python Tutorial. Python Software Foundation. [20 February 2012]. (原始內容存檔於2012-10-23).
It is a mixture of the class mechanisms found in C++ and Modula-3
- ^ Lundh, Fredrik. Call By Object. effbot.org. [21 November 2017]. (原始內容存檔於2019-11-23).
replace "CLU" with "Python", "record" with "instance", and "procedure" with "function or method", and you get a pretty accurate description of Python's object model.
- ^ Simionato, Michele. The Python 2.3 Method Resolution Order. Python Software Foundation. [2021-03-14]. (原始內容存檔於2020-08-20).
The C3 method itself has nothing to do with Python, since it was invented by people working on Dylan and it is described in a paper intended for lispers
- ^ Kuchling, A. M. Functional Programming HOWTO. Python v2.7.2 documentation. Python Software Foundation. [9 February 2012]. (原始內容存檔於2012-10-24).
- ^ Schemenauer, Neil; Peters, Tim; Hetland, Magnus Lie. PEP 255 – Simple Generators. Python Enhancement Proposals. Python Software Foundation. 18 May 2001 [9 February 2012]. (原始內容存檔於2020-06-05).
- ^ Smith, Kevin D.; Jewett, Jim J.; Montanaro, Skip; Baxter, Anthony. PEP 318 – Decorators for Functions and Methods. Python Enhancement Proposals. Python Software Foundation. 2 September 2004 [24 February 2012]. (原始內容存檔於2020-06-03).
- ^ More Control Flow Tools. Python 3 documentation. Python Software Foundation. [24 July 2015]. (原始內容存檔於2016-06-04).
- ^ CoffeeScript. coffeescript.org. [2021-03-14]. (原始內容存檔於2020-06-12).
- ^ The Genie Programming Language Tutorial. [28 February 2020]. (原始內容存檔於2020-06-01).
- ^ Perl and Python influences in JavaScript. www.2ality.com. 24 February 2013 [15 May 2015]. (原始內容存檔於2018-12-26).
- ^ Rauschmayer, Axel. Chapter 3: The Nature of JavaScript; Influences. O'Reilly, Speaking JavaScript. [15 May 2015]. (原始內容存檔於2018-12-26).
- ^ 28.0 28.1 Why We Created Julia. Julia website. February 2012 [2014-06-05]. (原始內容存檔於2020-05-02).
We want something as usable for general programming as Python [...]
- ^ Ring Team. Ring and other languages. ring-lang.net. ring-lang. 4 December 2017 [2021-03-14]. (原始內容存檔於2018-12-25).
- ^ Bini, Ola. Practical JRuby on Rails Web 2.0 Projects: bringing Ruby on Rails to the Java platform. Berkeley: APress. 2007: 3. ISBN 978-1-59059-881-8.
- ^ Lattner, Chris. Chris Lattner's Homepage. Chris Lattner. 3 June 2014 [3 June 2014]. (原始內容存檔於2018-12-25).
The Swift language is the product of tireless effort from a team of language experts, documentation gurus, compiler optimization ninjas, and an incredibly important internal dogfooding group who provided feedback to help refine and battle-test ideas. Of course, it also greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
- ^ 彼德·諾米格. Python for Lisp Programmers. [2020-04-21]. (原始內容存檔於2020-06-14).
Python can be seen as a dialect of Lisp with "traditional" syntax (what Lisp people call "infix" or "m-lisp" syntax).
- ^ Rossum, Guido Van. The History of Python: A Brief Timeline of Python. The History of Python. 2009-01-20 [2021-03-05]. (原始內容存檔於5 June 2020).
- ^ Peterson, Benjamin. Python Insider: Python 2.7.18, the last release of Python 2. Python Insider. 20 April 2020 [27 April 2020]. (原始內容存檔於26 April 2020).
- ^ Stack Overflow Developer Survey 2020. Stack Overflow. [2021-03-05]. (原始內容存檔於2 March 2021).
- ^ The State of Developer Ecosystem in 2020 Infographic. JetBrains: Developer Tools for Professionals and Teams. [2021-03-05]. (原始內容存檔於1 March 2021) (英語).
- ^ index | TIOBE - The Software Quality Company. www.tiobe.com. [2021-02-02]. (原始內容存檔於25 February 2018).
Python has won the TIOBE programming language of the year award! This is for the fourth time in the history, which is a record! The title is awarded to the programming language that has gained most popularity in one year.
- ^ PYPL PopularitY of Programming Language index. pypl.github.io. [2021-03-26]. (原始內容存檔於14 March 2017) (英語).
- ^ Guido van Rossum - Resume. [2022-10-12]. (原始內容存檔於2022-12-21).
- ^ Whetting Your Appetite. The Python Tutorial. Python Software Foundation. [2012-02-20]. (原始內容存檔於2012-10-26).
- ^ Benevolent dictator for life. Linux Format. 2005-02-01 [2007-11-01]. (原始內容存檔於2006-10-01).
- ^ Transfer of power. [2020-11-29]. (原始內容存檔於2018-07-12).
- ^ PEP 8100. python. Python Software Foundation. [2019-05-04]. (原始內容存檔於2020-06-04).
- ^ Steering Council nomination: Guido van Rossum (2020 term). [2020-10-11]. (原始內容存檔於2019-12-29).
- ^ HISTORY. Python source distribution. Python Foundation. [2017-11-23]. (原始內容存檔於2017-12-01).
- ^ The Making of Python. Artima Developer. [2007-03-22]. (原始內容存檔於2016-09-01).
- ^ van Rossum, Guido. The fate of reduce() in Python 3000. Artima Developer. [2007-03-22]. (原始內容存檔於2007-04-07).
- ^ LJ #37: Python 1.4 Update. [2007-04-29]. (原始內容存檔於2007-05-01).
- ^ Kuchling, A. M.; Zadka, Moshe. What's New in Python 2.0. Python Software Foundation. 2000-10-16 [2012-02-11]. (原始內容存檔於2012-10-23).
- ^ Hylton, Jeremy. PEP 227 -- Statically Nested Scopes. 2000-11-01 [2007-03-22]. (原始內容存檔於2007-03-29).
- ^ 51.0 51.1 51.2 Guido van Rossum. Unifying types and classes in Python 2.2. [2020-09-26]. (原始內容存檔於2019-09-28).
- ^ What’s New in Python 2.2 - PEP 234: Iterators. [2020-10-21]. (原始內容存檔於2021-02-07).
- ^ What’s New in Python 2.2 - PEP 255: Simple Generators. [2020-10-21]. (原始內容存檔於2021-02-07).
- ^ 54.0 54.1 What’s New in Python 2.2 - Descriptors. [2020-10-21]. (原始內容存檔於2021-02-07).
- ^ What’s New in Python 2.4 - PEP 318: Decorators for Functions and Methods. [2020-10-21]. (原始內容存檔於2021-02-07).
- ^ What’s New in Python 2.5 - PEP 343: The ‘with’ statement. [2020-10-21]. (原始內容存檔於2021-02-07).
- ^ Python 3.0 Release. Python Software Foundation. [2009-07-08]. (原始內容存檔於2020-06-14).
- ^ Automated Python 2 to 3 code translation — Python Documentation. [2018-02-11]. (原始內容存檔於2020-06-04).
- ^ van Rossum, Guido. PEP 3000 – Python 3000. Python Enhancement Proposals. Python Software Foundation. 2006-04-05 [2009-06-27]. (原始內容存檔於2016-03-03).
- ^ PEP 373 -- Python 2.7 Release Schedule. python.org. [2017-01-09]. (原始內容存檔於2020-05-19).
- ^ PEP 466 -- Network Security Enhancements for Python 2.7.x. python.org. [2017-01-09]. (原始內容存檔於2020-06-04).
- ^ macOS Monterey 12.3 Release Notes. [2022-03-25]. (原始內容存檔於2022-04-13).
- ^ Python Developer's Guide — Status of Python Version. devguide.python.org. [2022-08-26]. (原始內容存檔於2022-08-26).
- ^ PEP 8104 – 2023 Term Steering Council election. Python Software Foundation. [2022-12-15]. (原始內容存檔於2023-01-21).
- ^ 65.0 65.1 The Python Language Reference, section 3.3. Special method names. [2020-09-25]. (原始內容存檔於2012-10-26).
- ^ aspectlib. [2020-09-28]. (原始內容存檔於2014-11-05).
aspectlib is an aspect-oriented programming, monkey-patch and decorators library. It is useful when changing behavior in existing code is desired.
- ^ PEP 316 -- Programming by Contract for Python. [2021-01-17]. (原始內容存檔於2021-01-22).
- Deal. [2021-06-20]. (原始內容存檔於2021-07-16).
python library for design by contract (DbC) and checking values, exceptions, and side-effects.
- icontract. [2021-01-17]. (原始內容存檔於2021-01-21).
icontract provides design-by-contract to Python3 with informative violation messages and inheritance.
- PyContracts. [2021-01-17]. (原始內容存檔於2021-01-22).
PyContracts is a Python package that allows to declare constraints on function parameters and return values.
- dpcontracts. [2021-01-17]. (原始內容存檔於2021-01-22).
This module provides a collection of decorators that makes it easy to write software using contracts.
- Deal. [2021-06-20]. (原始內容存檔於2021-07-16).
- ^ PyDatalog. [2012-07-22]. (原始內容存檔於2020-06-13).
- ^ Extending and Embedding the Python Interpreter: Reference Counts. Docs.python.org. [2020-06-05]. (原始內容存檔於2012-10-18) (英語).
Since Python makes heavy use of
malloc()
andfree()
, it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called reference counting. - ^ Functional Programming HOWTO. [2020-09-26]. (原始內容存檔於2012-10-24).
- ^ 71.0 71.1 Hettinger, Raymond. PEP 289 – Generator Expressions. Python Enhancement Proposals. Python Software Foundation. 2002-01-30 [2012-02-19]. (原始內容存檔於2020-06-14).
- ^ Functional Programming Modules. Docs.python.org. [2020-09-26]. (原始內容存檔於2020-09-20).
- ^ Guido van Rossum. Foreword for "Programming Python" (1st ed.). 1996-05-01 [2020-09-12]. (原始內容存檔於2014-07-24) (英語).
- ^ ctypes — A foreign function library for Python. [2022-01-14]. (原始內容存檔於2022-04-27).
- ^ PEP 523 – Adding a frame evaluation API to CPython. [2022-08-29]. (原始內容存檔於2022-08-29).
- ^ Style Guide for Python Code: indentation. [2020-09-26]. (原始內容存檔於2018-07-13).
- ^ 2. Lexical analysis. Python v3.8.6 documentation. Docs.python.org. [2020-09-26]. (原始內容存檔於2018-01-09).
- ^ 2. Lexical analysis. Python v2.7.18 documentation. Docs.python.org. [2020-09-26]. (原始內容存檔於2019-05-08).
- ^ New Keywords. Python v3.5 documentation. Docs.python.org. [2016-06-01]. (原始內容存檔於2016-06-18).
- ^ Naming Conventions. [2017-10-06]. (原始內容存檔於2018-07-13).
- ^ 81.0 81.1 9.6. Private Variables. [2020-09-27]. (原始內容存檔於2012-10-23).
- ^ 82.0 82.1 PEP 342 -- Coroutines via Enhanced Generators. [2019-11-21]. (原始內容存檔於2020-05-29).
- ^ PEP 380 -- Syntax for Delegating to a Subgenerator. [2019-11-21]. (原始內容存檔於2020-06-04).
- ^ Highlights: Python 2.5. Python.org. [2020-09-21]. (原始內容存檔於2019-08-04).
- ^ Hamblen, Diane. Only the Limits of Our Imagination: An exclusive interview with RADM Grace M. Hopper. Department of the Navy Information Technology Magazine. [2007-01-31]. (原始內容存檔於2009-01-14).
- ^ "It is Easier to Ask for Forgiveness than Permission" EAFP (頁面存檔備份,存於網際網路檔案館), Python Glossary
- ^ Alex Martelli. Python in a nutshell. : 134 [2020-09-26]. (原始內容存檔於2022-05-13).
- ^ The "with" Statement. [2020-09-26]. (原始內容存檔於2014-12-14).
- ^ van Rossum, Guido. Tail Recursion Elimination. Neopythonic.blogspot.be. 2009-04-22 [2012-12-03]. (原始內容存檔於2018-05-19).
van Rossum, Guido. Language Design Is Not Just Solving Puzzles. Artima forums. Artima. 2006-02-09 [2007-03-21]. (原始內容存檔於2020-01-17). - ^ Thomas Baruchel. tco-Tail Call Optimization for Python. [2021-10-14]. (原始內容存檔於2022-04-15).
The module allows a coder to write tail-recursive functions as well as using continuation-passing style in his/her code without having the size of the execution stack increasing.
- ^ PEP 3156 -- Asynchronous IO Support Rebooted: the "asyncio" Module. [2019-11-21]. (原始內容存檔於2019-11-14).
- ^ Generator-based Coroutines. [2020-10-29]. (原始內容存檔於2018-12-31).
Support for generator-based coroutines is deprecated and is scheduled for removal in Python 3.10.
- ^ PEP 492 -- Coroutines with async and await syntax. [2019-11-21]. (原始內容存檔於2019-01-05).
- ^ What’s New In Python 3.7. [2019-11-21]. (原始內容存檔於2019-11-28).
- ^ 95.0 95.1 95.2 Python.org: Modules. [2020-10-30]. (原始內容存檔於2021-02-06).
- ^ 96.0 96.1 Python.org: The import Statement. [2020-10-30]. (原始內容存檔於2021-02-07).
- ^ Python.org: __main__. [2020-10-30]. (原始內容存檔於2021-02-07).
- ^ Python.org: Dir(). [2020-09-25]. (原始內容存檔於2018-10-26).
- ^ division. python.org. [2014-10-17]. (原始內容存檔於2006-07-20).
- ^ Python 3.5.1 Release and Changelog. python.org. [2016-01-01]. (原始內容存檔於2020-05-14).
- ^ 101.0 101.1 PEP 0465 -- A dedicated infix operator for matrix multiplication. python.org. [2016-01-01]. (原始內容存檔於2020-06-04).
- ^ numpy.matmul. [2022-01-18]. (原始內容存檔於2022-04-10).
- ^ Chapter 15. Expressions - 15.21.1. Numerical Equality Operators == and !=. Oracle Corporation. [2016-08-28]. (原始內容存檔於2020-06-07).
- ^ Chapter 15. Expressions - 15.21.3. Reference Equality Operators == and !=. Oracle Corporation. [2016-08-28]. (原始內容存檔於2020-06-07).
- ^ What’s New in Python 3.8 - Assignment expressions. [2019-10-14]. (原始內容存檔於2020-06-08).
- ^ What’s New in Python 3.9 - Dictionary Merge & Update Operators. [2021-06-12]. (原始內容存檔於2020-10-07).
- ^ 4. Built-in Types — Python 3.6.3rc1 documentation. python.org. [2017-10-01]. (原始內容存檔於2020-06-14).
- ^ 5.3. Tuples and Sequences — Python 3.7.1rc2 documentation. python.org. [2018-10-17]. (原始內容存檔於2020-06-10).
- ^ 109.0 109.1 PEP 498 -- Literal String Interpolation. python.org. [2017-03-08]. (原始內容存檔於2020-06-15).
- ^ 2. Lexical analysis. Python v2.7.5 documentation. Docs.python.org. [2013-08-16]. (原始內容存檔於2012-10-23).
- ^ Positional-only parameters. [2020-09-24]. (原始內容存檔於2020-06-08).
- ^ Python 2.4 Decorators: Reducing code duplication and consolidating knowledge. Dr. Dobb's. 2005-05-01 [2007-02-08]. (原始內容存檔於2007-02-06).
- ^ New Tail Recursion Decorator. ASPN: Python Cookbook. 2006-11-14 [2007-02-08]. (原始內容存檔於2007-02-09).
- ^ The decorator module. [2007-02-08]. (原始內容存檔於2007-02-10).
- ^ PEP 484 -- Type Hints. [2021-03-01]. (原始內容存檔於2021-02-09).
- ^ PEP 3107 -- Function Annotations. [2021-03-01]. (原始內容存檔於2015-01-06).
- ^ The Cain Gang Ltd. Python Metaclasses: Who? Why? When? (PDF). [2009-06-27]. (原始內容 (PDF)存檔於2009-05-30).
- ^ Special Attributes. [2020-09-12]. (原始內容存檔於2020-06-14).
- ^ Why must 'self' be used explicitly in method definitions and calls?. Design and History FAQ. Python Software Foundation. [2012-02-19]. (原始內容存檔於2012-10-24).
- ^ super().method, in Python 3. [2020-09-25]. (原始內容存檔於2018-10-26).
- ^ Descriptor HowTo Guide. [2020-09-26]. (原始內容存檔於2020-09-18).
- ^ Built-in Functions: property. [2020-09-25]. (原始內容存檔於2018-10-26).
- ^ The Python Language Reference, section 3.3. New-style and classic classes, for release 2.7.18. [2020-09-25]. (原始內容存檔於2020-05-05).
- ^ Type hinting for Python. LWN.net. 2014-12-24 [2015-05-05]. (原始內容存檔於2019-06-20).
- ^ mypy - Optional Static Typing for Python. [2017-01-28]. (原始內容存檔於2020-06-06).
- ^ 。實際受限於機器的記憶體大小Zadka, Moshe; van Rossum, Guido. PEP 237 – Unifying Long Integers and Integers. Python Enhancement Proposals. Python Software Foundation. 2001-03-11 [2011-09-24]. (原始內容存檔於2020-05-28).
- ^ 15. Floating Point Arithmetic: Issues and Limitations — Python 3.8.3 documentation. docs.python.org. [2020-06-06]. (原始內容存檔於2020-06-06).
almost all platforms map Python floats to IEEE-754 double precision
- ^ Built-in Types. [2019-10-03]. (原始內容存檔於2020-06-14).
- ^ Zadka, Moshe; van Rossum, Guido. PEP 238 – Changing the Division Operator. Python Enhancement Proposals. Python Software Foundation. 2001-03-11 [2013-10-23]. (原始內容存檔於2020-05-28).
- ^ round, The Python standard library, release 3.2, §2: Built-in functions, [2011-08-14], (原始內容存檔於2012-10-25)
- ^ Beazley, David M. Python Essential Reference 4th. 2009: 66.
- ^ Kernighan, Brian W.; Ritchie, Dennis M. The C Programming Language 2nd. 1988: 206.
- ^ Batista, Facundo. PEP 0327 -- Decimal Data Type. Python.org. [2015-09-26]. (原始內容存檔於2020-06-04).
- ^ What's New in Python 2.6 — Python v2.6.9 documentation. docs.python.org. [2015-09-26]. (原始內容存檔於2019-12-23).
- ^ 10 Reasons Python Rocks for Research (And a Few Reasons it Doesn't) – Hoyt Koepke. www.stat.washington.edu. [2019-02-03]. (原始內容存檔於2020-05-31).
- ^ Shell, Scott. An introduction to Python for scientific computing (PDF). 2014-06-17 [2019-02-03]. (原始內容存檔 (PDF)於2019-02-04).
- ^ Przemyslaw Piotrowski, Build a Rapid Web Development Environment for Python Server Pages and Oracle (頁面存檔備份,存於網際網路檔案館), Oracle Technology Network, July 2006. Accessed October 21, 2008.
- ^ Python Interpreters Benchmarks. [2022-08-30]. (原始內容存檔於2022-08-20).
- ^ CPython byte code. Docs.python.org. [2016-02-16]. (原始內容存檔於2020-06-05).
- ^ Python 2.5 internals (PDF). [2011-04-19]. (原始內容存檔 (PDF)於2012-08-06).
- ^ The Computer Language Benchmarks Game. [2020-04-30]. (原始內容存檔於2020-06-14).
- ^ Pyston - A faster and highly-compatible implementation of the Python programming language. [2022-08-29]. (原始內容存檔於2022-08-29).
- ^ Announcing 3.7-3.10 support and a new direction. September 29, 2022 [2023-01-15]. (原始內容存檔於2023-01-15).
We’re very excited to announce that today we are releasing a new version of Pyston-lite, our Python JIT-as-an-extension-module, with the headline feature of supporting Python versions 3.7 through 3.10 (Mac and Linux). Previously we only supported Python 3.8, and support for other versions was one of our most-requested features.
- ^ 144.0 144.1 Cinder is Meta's internal performance-oriented production version of CPython. [2022-08-26]. (原始內容存檔於2021-05-04).
- ^ Pyjion - A JIT for Python based upon CoreCLR. [2022-08-29]. (原始內容存檔於2022-08-29).
- ^ Nuitka the Python Compiler. [2020-09-26]. (原始內容存檔於2022-09-03).
- ^ Pythran - Ahead of Time compiler for numeric kernels. [2022-08-29]. (原始內容存檔於2022-08-29).
- ^ XONSH is a Python-powered shell. [2022-08-28]. (原始內容存檔於2022-09-03).
- ^ Tool recommendations. python.org. [21 April 2022]. (原始內容存檔於2022-09-06) (英語).
- ^ Pipenv: Python Development Workflow for Humans. [2022-08-29]. (原始內容存檔於2019-11-17).
- ^ pyenv - Simple Python version management. [2022-08-30]. (原始內容存檔於2022-09-08).
- ^ 152.0 152.1 TIOBE Index. TIOBE - The Software Quality Company. [2021-10-06]. (原始內容存檔於2020-06-14).
- ^ FAQ: Django appears to be a MVC framework, but you call the Controller the “view”, and the View the “template”. How come you don’t use the standard names?. [2022-09-01]. (原始內容存檔於2022-09-02).
- ^ Asynchronous HTTP Client/Server for asyncio and Python. [2021-01-14]. (原始內容存檔於2021-01-15).
- ^ gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev or libuv event loop. [2021-03-13]. (原始內容存檔於2021-06-07).
- ^ Remi - Python REMote Interface library. [2022-08-28]. (原始內容存檔於2022-08-28).
- ^ PySimpleGUI - Python GUIs for Humans. [2022-08-28]. (原始內容存檔於2022-08-28).
- ^ Gooey - Turn (almost) any Python command line program into a full GUI application with one line. [2022-08-28]. (原始內容存檔於2022-08-28).
- ^ Pyforms - Python layer of Windows forms, based on PyQt and OpenGL. [2022-08-28]. (原始內容存檔於2022-08-28).
- ^ CuPy: NumPy & SciPy for GPU. [2022-08-31]. (原始內容存檔於2022-08-31).
- ^ DataFrame. [2022-09-01]. (原始內容存檔於2022-09-01).
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.
- ^ Dask - Parallel computing with task scheduling. [2022-08-31]. (原始內容存檔於2022-08-31).
- ^ Joblib: running Python functions as pipeline jobs. [2022-09-19]. (原始內容存檔於2022-12-07).
- ^ Thread-pool Controls. [2022-09-19]. (原始內容存檔於2022-11-02).
- ^ Plotly.js - Open-source JavaScript charting library behind Plotly and Dash. [2022-09-21]. (原始內容存檔於2022-12-21).
- ^ Dash - Analytical Web Apps for Python, R, Julia, and Jupyter. [2022-09-21]. (原始內容存檔於2022-12-05).
- ^ Streamlit — The fastest way to build data apps in Python. [2022-09-21]. (原始內容存檔於2023-01-17).
- ^ Panel - A high-level app and dashboarding solution for Python. [2022-09-21]. (原始內容存檔於2023-01-16).
- ^ Voilà - Voilà turns Jupyter notebooks into standalone web applications. [2022-09-21]. (原始內容存檔於2022-12-31).
- ^ Dashboarding tools. [2022-09-21]. (原始內容存檔於2022-09-28).
- ^ TensorFlow API Documentation - Module: tf. [2022-08-31]. (原始內容存檔於2022-09-05).
- ^ TensorFlow API Documentation - Module: tf.keras. [2022-08-31]. (原始內容存檔於2020-01-22).
- ^ SciKeras - Scikit-Learn API wrapper for Keras. [2022-09-01]. (原始內容存檔於2022-06-19).
- ^ skorch - A scikit-learn compatible neural network library that wraps PyTorch. [2022-09-01]. (原始內容存檔於2022-08-24).
- ^ JAX - Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more. [2022-08-28]. (原始內容存檔於2021-02-05).
- ^ Autograd - Efficiently computes derivatives of numpy code. [2022-08-28]. (原始內容存檔於2022-07-18).
- ^ XLA: Optimizing Compiler for Machine Learning. [2022-08-28]. (原始內容存檔於2022-09-01).
- ^ Flax is a neural network library for JAX that is designed for flexibility. [2022-08-31]. (原始內容存檔於2022-09-03).
- ^ NumPyro - Probabilistic programming with NumPy powered by JAX for autograd and JIT compilation to GPU/TPU/CPU. [2022-08-31]. (原始內容存檔於2022-08-31).
- ^ Brax - Massively parallel rigidbody physics simulation on accelerator hardware. [2022-08-31]. (原始內容存檔於2022-08-31).
- ^ Ray - Effortlessly scale your most complex workloads. [2022-09-19]. (原始內容存檔於2022-12-13).
- ^ Mars is a tensor-based unified framework for large-scale data computation which scales numpy, pandas, scikit-learn and Python functions. [2022-09-19]. (原始內容存檔於2023-01-06).
- ^ Pillow: a modern fork of PIL. [December 8, 2013]. (原始內容存檔於2016-04-27).
- ^ PyOpenGL is the most common cross platform Python binding to OpenGL and related APIs. [2022-01-07]. (原始內容存檔於2011-06-15).
- ^ ModernGL - Modern OpenGL binding for python. [2022-01-07]. (原始內容存檔於2022-04-15).
- ^ VisPy - interactive scientific visualization in Python. [2022-08-30]. (原始內容存檔於2022-07-13).
- ^ CUDA Python Manual. [2022-08-30]. (原始內容存檔於2022-08-30).
- ^ PyCUDA gives you easy, Pythonic access to Nvidia’s CUDA parallel computation API. [2022-05-29]. (原始內容存檔於2022-06-28).
- ^ PyOpenCL gives you easy, Pythonic access to the OpenCL parallel computation API. [2021-07-29]. (原始內容存檔於2022-03-08).
- ^ Kornia - Open Source Differentiable Computer Vision Library. [2022-09-22]. (原始內容存檔於2023-01-10).
- ^ SDL Language Bindings. [2022-02-16]. (原始內容存檔於2019-03-12).
- ^ pythonnet - Python.NET. [2022-08-30]. (原始內容存檔於2022-09-01).
- ^ Fabric - Pythonic remote execution. [2013-04-08]. (原始內容存檔於2014-04-11).
- ^ Prefect - The easiest way to coordinate your dataflow. [2022-09-22]. (原始內容存檔於2023-01-11).
- ^ PyInstaller. [2021-03-13]. (原始內容存檔於2021-06-07).
- ^ 4.0 New Features and Fixes. LibreOffice.org. The Document Foundation. 2013 [25 February 2013]. (原始內容存檔於9 February 2014).
- ^ Panda3D Manual. [2022-09-04]. (原始內容存檔於2018-12-29).
- ^ Python Discord is a large community focused around the Python programming language. [2021-01-13]. (原始內容存檔於2021-02-01).
- ^ Gotchas for Python Users. boo.codehaus.org. Codehaus Foundation. [2008-11-24]. (原始內容存檔於2008-12-11).
- ^ Esterbrook, Charles. Acknowledgements. cobra-language.com. Cobra Language. [2010-04-07]. (原始內容存檔於2008-02-08).
- ^ Proposals: iterators and generators [ES4 Wiki]. wiki.ecmascript.org. [2008-11-24]. (原始內容存檔於2007-10-20).
- ^ FAQ: What is GDScript and why should I use it?. [2020-09-13]. (原始內容存檔於2020-05-19).
- ^ Kincaid, Jason. Google's Go: A New Programming Language That's Python Meets C++. TechCrunch. 2009-11-10 [2010-01-29]. (原始內容存檔於2010-01-18).
- ^ Strachan, James. Groovy – the birth of a new dynamic language for the Java platform. 2003-08-29 [2007-06-11]. (原始內容存檔於2007-04-05).
- ^ Yegulalp, Serdar. Nim language draws from best of Python, Rust, Go, and Lisp. InfoWorld. 2017-01-16 [2020-09-13]. (原始內容存檔於2018-10-13).
Nim's syntax is strongly reminiscent of Python's, as it uses indented code blocks and some of the same syntax (such as the way if/elif/then/else blocks are constructed).
- ^ Lattner, Chris. Chris Lattner's Homepage. Chris Lattner. 2014-06-03 [2014-06-03]. (原始內容存檔於2015-12-22).
I started work on the Swift Programming Language in July of 2010. I implemented much of the basic language structure, with only a few people knowing of its existence. A few other (amazing) people started contributing in earnest late in 2011, and it became a major focus for the Apple Developer Tools group in July 2013 [...] drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
- ^ An Interview with the Creator of Ruby. Linuxdevcenter.com. [2012-12-03]. (原始內容存檔於2018-04-28).
延伸閱讀[編輯]
- John Denero. SICP in Python - CS61A: Online Textbook. 2012-03-21 [2020-10-09]. (原始內容存檔於2020-05-30).SICP Python 描述 中文版. 由飛龍翻譯. [2020-10-09]. (原始內容存檔於2020-04-21).
- John DeNero. Composing Programs, a free online introduction to programming and computer science. [2020-10-09]. (原始內容存檔於2021-01-28).
- Downey, Allen B. Think Python: How to Think Like a Computer Scientist Version 1.6.6. May 2012. ISBN 978-0-521-72596-5.
- Lutz, Mark. Learning Python 5th. O'Reilly Media. 2013. ISBN 978-0-596-15806-4.
參閲[編輯]
外部連接[編輯]
![]() |
維基共享資源上的多媒體資源 |
![]() |
維基語錄上的名言 |
![]() |
維基教科書上的教科書和手冊 |
![]() |
維基學院上的學習資源 |
- 官方網站
- Awesome Python (頁面存檔備份,存於網際網路檔案館)
- Real Python Tutorials (頁面存檔備份,存於網際網路檔案館)
- programingz - Learn Python Programming (頁面存檔備份,存於網際網路檔案館)
- w3schools - Python Tutorial (頁面存檔備份,存於網際網路檔案館)
- ItsMyCode- Learn Python Programming (頁面存檔備份,存於網際網路檔案館)
- Codecary - Learn Python Programming (頁面存檔備份,存於網際網路檔案館)
- dainikchorcha - Learn Python Programming(頁面存檔備份,存於網際網路檔案館)
- Tutlane - Learn Python Online (頁面存檔備份,存於網際網路檔案館)
|
|
|
|
|