fbpx
维基百科

Python

Python英國發音:/ˈpaɪθən/美國發音:/ˈpaɪθɑːn/),是一种广泛使用的解释型高级通用编程语言。Python支持多种编程范型,包括函数式、指令式、反射式、结构化和面向对象编程。它拥有动态类型系统垃圾回收功能,能够自动管理内存使用,并且其本身拥有一个巨大而广泛的标准库。它的语言结构以及面向对象的方法,旨在帮助程序员为小型的和大型的项目编写逻辑清晰的代码。

Python
编程范型多范型函数式指令式反射式结构化面向对象
設計者吉多·范罗苏姆
實作者Python软件基金会
发行时间1991年,​32年前​(1991[1]
穩定版本
3.11.1[2]
(2022年12月6日,32天前 )
預覽版本
3.12.0a3[2]
(2022年12月6日,32天前 )
型態系統鸭子类型动态强类型[3]渐进英语gradual typing(自从3.5)[4]
作業系統跨平臺WindowsLinux/UnixmacOS
許可證Python软件基金会许可证
文件扩展名.py、.pyi、.pyc、.pyd、.pyo(3.5之前)[5]、.pyw、.pyz(自从3.5)[6]
網站www.python.org
主要實作產品
CPythonPyPyIronPythonJythonStackless PythonMicroPythonCircuitPython英语CircuitPython、RustPython[7]
衍生副語言
CythonRPythonStarlark英语Bazel (software)[8]
啟發語言
ABC[9]Ada[10]ALGOL 68[11]APL[12]C[13]C++[14]CLU[15]Dylan[16]Haskell[17]Icon[18]Java[19]Lisp[20]Modula-3[14]PerlStandard ML[12]
影響語言
BooCobra英语Cobra (programming language)CoffeeScript[21]DF#FalconGenie[22]GoGroovyJavaScript[23][24]Julia[25]Nim、Ring[26]Ruby[27]Swift[28]

吉多·范罗苏姆于1980年代后期开始研发Python,作为ABC语言的后继者,它也可以被视为采用了叫做M-表达式英语M-expression中缀表示法的一种LISP方言[29]吉多·范罗苏姆于1991年首次发布 Python 0.9.0[30]。Python 2.0于2000 年发布并引入了新功能。Python 3.0于2008年发布,它是该语言的主要修订版,并非完全向后兼容。Python 2于2020年随2.7.18版停止支持[31]

Python的设计哲学,强调代码的可读性和简洁的语法,尤其是使用空格缩进来划分代码块。相比於CJava,Python让开发者能够用更少的代码表达想法。

Python解释器本身几乎可以在所有的操作系统中运行,它的官方直譯器CPython是用C语言编写的。Python是一個由社群驱动的自由软件,目前由Python软件基金会管理。Python是最受欢迎的编程语言之一[32][33][34][35]

歷史

 
Python創始人吉多·范羅蘇姆在2006年的照片

Python的創始人吉多·范羅蘇姆,在1982年至1995年间,参与了荷兰数学和计算机科学研究学会多个项目的工作[36]。1989年的聖誕節期間,他決心開發一個新的腳本解釋程式,作為ABC語言的繼承者,并且用它替代Unix shellC语言来进行系统管理,担负与Amoeba操作系统英语Amoeba (operating system)之间的交互操作并进行异常处理[9]。他是BBC電視劇《Monty Python的飛行馬戲團》的爱好者,所以选取了Python作为这个编程语言的名字[37]。范羅蘇姆作为Python的主要開發者,独自担负这个项目的发展决策者职责,直到2018年7月12日,他宣布从終身仁慈獨裁者(BDFL)的职权上“永久休假”[38][39]。他在2019年1月至11月参与了第一届五人掌控委员会继续领导项目发展[40][41]

在1991年2月,范羅蘇姆在alt.sources上发布了最初代码(标记为版本0.9.0)[42],这时就已经存在了带继承的异常处理函数和核心数据类型listdictstr等。在这个最初发行中就有了从Modula-3引进的模块系统[43],它的异常模型也类似于Modula-3[9]。在1994年1月Python达到了版本1.0。这个发行版主要新特征是包括了由Amrit Prem提供的函数式编程工具lambdamapfilterreduce[44]。Python 1.4增加了受Modula-3启发的关键字参数英语Named parameter,和对复数的内建支持,还包含了采取名字修饰的一种基本形式的数据隐藏英语Information hiding[45]

Python 2.0於2000年10月16日發布,介入了列表推导式,这是从函数式编程语言SETLHaskell中引入的。它还向垃圾回收系统增加了检测算法,并且支持Unicode[46]。Python 2.1支持了嵌套作用域,就像其他静态作用域语言一样[47]。Python 2.2的重大革新是将Python的类型(用C写成)和(用Python写成)统一入一个层级,使得Python的对象模型成为纯粹和一致的面向对象的模型[48];还增加了迭代器[49],受CLUIcon启发的生成器[50],和描述器协议[51]。Python 2.4加入了集合英语Set (abstract data type)数据类型,和函数修饰器[52]。Python 2.5加入了with语句[53]

Python 3.0於2008年12月3日發布,它对语言做了较大修订而不能完全后向兼容[54]。Python 3发行包括了2to3实用工具,它(至少部份的)自动将Python 2代码转换成Python 3代码[55]。Python 3的很多新特性後來也被移植到舊的Python 2.6/2.7版本中[56]

Python 2.7的产品寿命结束日期最初设定为2015年,出于对大量的现存代码不能前向移植到Python 3的关切,而将对它的支持延期至2020年[57][58]。随着Python 2的产品寿命结束,2022年3月14日发布的macOS 12.3已经彻底移除了Python 2[59]。当前只有Python 3的稳定版本3.10、3.11和预览版本3.12正在被完全支持,但仍提供对3.7、3.8和3.9版本的安全性修正[60]

在2022年12月,活跃的Python核心开发者选举Pablo Galindo Salgado、Gregory P. Smith、Emily Morehouse、Brett Cannon和Thomas Wouters为2023年度“掌控委员会”的五位成员来领导这个项目[61]

特徵與設計哲學

Python是多范型编程语言。它完全支持结构化编程面向对象编程,还有很多特征支持函数式编程元编程比如元对象协议元类和魔术方法[62])。通过扩展还可以支持很多范型,包括面向切面编程[63]契约式设计[64]逻辑编程[65]

Python使用动态类型,在内存管理上采用引用计数和环检测相结合的垃圾回收器[66]。它的特征还有动态名字解析后期绑定英语late binding),即在程序执行期间绑定方法和变量的名字。

Python對遵循LISP傳統的函数式编程提供了有限的支持[67],它提供了 mapfilterreduce函数;列表推导式字典集合英语Set (abstract data type)生成器表达式[68]。標準庫中的模組functoolsitertools,实现了从HaskellStandard ML借鉴来的函數式工具[69]

Python的設計理念是“優雅”、“明確”、“簡單”,它的一些重要準被合稱為「Python之禅」。在Python解釋器内運行import this可以獲得完整的列表,下面举出其中首要:

  • 优美优于丑陋。明瞭优于隐晦。
  • 简单优于复杂。复杂优于凌乱。
  • 扁平优于嵌套。稀疏优于稠密。
  • 可读性很重要。

Python開發者的方法论是“用一種方法,最好是只有一種方法來做一件事”,显著不同于以Perl语言为代表的“不止一种方法去做一件事”風格。Python開發者在設計語言時,如果面臨多種選擇,一般會拒绝花俏的語法,而選擇明確没有或者很少有歧義的語法。

范羅蘇姆认为ABC語言非常優美和强大,它没有取得成功的原因是不開放造成的[70],故而将Python本身設計為可擴充的。Python並不把所有的特性和功能都集成到語言核心,而是提供了豐富的API和工具,以便程式設計師能够輕鬆地使用Python、CCython來編寫擴充模組。Python还可以通过外界函数接口英语Foreign function interface如标准库中的ctypes等,来访问动态链接库共享库中C兼容数据类型并调用其中函数[71],以便于对用其他語言編寫的程式進行集成和封裝。

Python開發人員盡量避開不成熟或者不重要的優化。一些針對非重要部位的加快運行速度的補丁,通常不會被合併到Python的官方实现CPython中。在某些對運行速度要求很高的情況,可以使用JIT技术的Python实现或扩展[72]

語法

Python的設計目標之一是讓程式碼具備高度的可閱讀性。它設計時盡量使用其它語言經常使用的標點符號和英文單字,讓程式碼看起来整潔美觀。Python语句之后的分号是可选的,作为动态语言不需要書寫“聲明”語句,不同於其他的靜態語言如CPascal

縮排

Python語言利用縮排表示語句塊的開始和結束(越位規則),而非使用大括號或者某種關鍵字。增加縮排表示語句塊的開始,而減少縮排則表示語句塊的結束。根據PEP 8的規定[73],使用4個空格來表示每級縮排。[a]

使用Tab字符和其它數目的空格雖然都可以被解釋器識別,但不符合編碼規範,偏向使用Tab字符的程序員可以設置文本編輯器將Tab鍵轉換為4個空格。縮排成為了語法的一部分,並且Python開發者有意讓違反了「縮排規則」的程序不能通過解釋。

关键字

Python有如下35个关键字或“保留字”;它们不能用作标识符[74][75]

  • and
  • as
  • assert
  • async[注 1]
  • await[注 1]
  • break
  • class
  • continue
  • def
  • del
  • elif
  • else
  • except
  • False[注 2]
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • None
  • nonlocal[注 2]
  • not
  • or
  • pass
  • raise
  • return
  • True[注 2]
  • try
  • while
  • with
  • yield
注释
  1. ^ 1.0 1.1 从Python 3.5开始,介入了asyncawait[76]
  2. ^ 2.0 2.1 2.2 从Python 3开始,介入了关键字TrueFalsenonlocal

标识符

标识符就是名字,在ASCII范围内(U+0001..U+007F),可用于标识符的字符为:大写字母AZ和小写字母az,下划线_以及数字09,但首字不可以用数字。有如下命名约定[77]

  • _spam(单下划线开头):弱“内部使用”标识。对于from M import *,将不导入所有以下划线开头的对象。
  • spam_(单下划线结尾):为了避免与python关键字的命名冲突。
  • __spam(双下划线开头):在命名一个类特性的时候,采用名字修饰,比如在类SpamEggs内,__spam将变成_SpamEggs__spam[78]
  • __spam__(双下划线开头双下划线结尾):指那些包含在用户控制的命名空间中的“魔术”方法或特性,比如__name____doc____init____import____file__等。建议永远不要将这样的命名方式应用于自己的变量或函数。

在Python文献中经常使用的元语法变量英语metasyntactic variablespam和eggs英语Spam (Monty Python)而非传统的foo和bar[78]

語句和控制流

Python的语句包括:

  • 赋值语句,记号为等号=。Python支持并行赋值,可以同时给多个变量赋值,还可以交换两个变量的值。[b]
  • del语句,递归的进行删除。
  • pass語句,充当NOP,表示此行為空,不執行任何操作。
  • assert語句,用於程式調適階段時測試執行條件是否滿足。
  • if語句,當條件成立時執行語句塊。經常與elifelse配合使用。
  • for語句,遍历列表、字符串、字典、集合等迭代器,依次處理迭代器中的每個元素。
  • while語句,當條件為真時,循環執行語句塊。
  • break语句,从循环中跳出。
  • continue语句,越过这次迭代并继续进行下个项目。
  • try英语Exception handling syntax語句,與exceptelsefinally配合使用,處理在程式執行中出现的異常情況。
  • raise语句,抛出一个异常。
  • class語句,用於定義,它执行一块代码并将它的局部命名空间附属至一个类。
  • def語句,用於定義函數方法
  • return语句,用来从函数返回值。
  • yield语句,使用它从一个生成器中返回一个值。[c]在版本2.5之前,生成器是惰性迭代器,信息是单向的从生成器传递出来的。自从版本2.5,yield也是一个有返回值的运算符,能够将信息传递回到生成器函数中[79]。自从版本3.3,信息可以传递通过多个堆栈层级[80]
  • with語句,把一块代码包裹在一个上下文管理器之内。例如,在一块代码执行之前获取一个并且在此后释放这个锁,或打开一个文件并且在此后关闭它。它允许了资源获取即初始化(RAII)式行为并可替代常见的try/finally惯用法[81]
  • 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[82]:“请求原谅比许可更容易”[83][84]。Python使用with语句处理资源[85],在进入一个作用域的时候调用一个函数而在离开它的时候调用另一个函数。这能防止忘记移除资源并且还可处理更复杂的状况比如异常。[e]

Python官方实现不提供尾调用优化或头等续体,吉多·范罗苏姆曾声称永远都不会加以支持[86],目前只有第三方库支持[87]。Python在版本2.5中通过扩展生成器,提供了对协程式功能的更好支持[79][f]版本3.4介入了综合性的异步I/O框架标准化,在其中扩展了利用子生成器委托的协程[88],这个扩展自从Python 3.8被弃用[89]。Python 3.5通过async/await语法介入了对协程的显式支持[90]。从版本3.7开始async/await成为保留关键字[91][g]

模块是定义可以被导入并重用于其他Python程序中的函数和类的Python正规.py文件[92]import语句找到一个模块,装载它,如果有需要的话初始化它,并且定义用来引用这个模块中代码的一个名字或一些名字[93]from...import语句,找到、装载、必需时初始化一个模块,接着增加模块引用到局部命名空间,允许访问其中的函数和类而不采用模块引用[93]from ... import支持*选项来导入所有引用而非指名的特定函数或类[92]。当模块被导入的时候,__name__变量被设置成这个模块的名字。在Python解释器直接运行一个模块的时候,__name__变量被设置为"__main__"。这允许被设计用于导入的模块增加只在模块被直接运行时候执行的代码[92][94]dir()函数返回在当前局部作用域中或参数指定的对象中的名字的列表[95]

表达式

Python中很多表达式与Cjava类似,而另一些则与之不同。

  • 在Python中,算术运算的加法+、减法-、乘法*取模%是与Cjava相同的,但是除法的行为不同。在Python中有两种除法,它们是下取整除法(或整数除法)//和浮点除法/[96] 。Python增加了指数算符**。Python有如下必须用于整数的运算:&与(AND),|或(OR),~非(NOT),^异或(XOR),>>右移, <<左移。自从Python 3.5[97],介入了新的@中缀矩阵乘法算符[98],它已经用于了NumPy[99]
  • 在Python中,有如下比较运算:大于>,小于<,等于==,不等于!=,小于等于<=,大于等于 >===按值比较,对比于Java,它按值比较数[100]而按引用比较对象[101](在Java中比较对象的值可以采用equals()方法)。Python的isis not算符可以用来比较对象的同一性(按引用比较),也就是比较两个变量是否引用了同一个对象。而innot in用于判断一个对象是否属于另外一个对象。在Python中,比较是可以链接起来的,比如a <= b <= c
  • Python使用andornot表示逻辑运算与、或、非,不采用Java和C中所用的符号&&||!
  • 自从Python 3.8,介入了“赋值表达式”语法:=。它也叫做“命名表达式”或“海象”,它将一个表达式赋值给一个标识符,同时还返回这个表达式的值,常用作更大的表达式的一部份[102]
  • 自从Python 3.9,介入了字典归并算符|和更新算符|=[103]
  • 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,)[104]。列表是可变的,并且不能用作字典的键(Python中字典的键必须是不可变的)。元组是不可变的,因而可以用作字典的键,假定这个元组的所有元素都是不可变的话。可以使用+算符来串接二个元组,这不会直接修改它们的内容,而是产生包含给定元组二者的元素的一个新元组。因此,给定变量t初始时等于(1, 2, 3),执行t = t + (4, 5)时,首先求值t + (4, 5),它产生(1, 2, 3, 4, 5),接着赋值回到t,这在效果上“修改了”t的内容,尽管这还是遵守了元组对象的不可变本性。
  • Python有“序列解包”特征,多个表达式,其中每个都可求值成能被赋值的东西(变量、可写的属性等),以与形成元组文字(literal)相同的方式,关联起来作为一个整体,放置在赋值语句等号的左手侧。这个语句预期在等号的右手侧有一个“可迭代”对象,在迭代它的时候产生同左手侧给出的可写表达式相同数目的值,这个语句对它进行迭代并把每个产生的值赋值给左手侧对应的表达式[105]。这个特征允许从一个单一函数返回多个值。自从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-字符串”[106]blah = "blah"; eggs = 2; f'spam={blah} eggs={eggs}'[m]
  • Python拥有各种字符串文字英语string literal:
    • 由单引号'或双引号"界定的字符串。不同于Unix shellPerl和受Perl影响的语言,单引号和双引号功能相同。这二种字符串都使用反斜杠\作为转义字符。在Python 3.6中字符串插值英语String interpolation可作为“格式化字符串”而获得到[106]
    • 三引号字符串,开始和结束于三个单引号或双引号的序列。它们可以跨越多行,其功能就像shell、Perl和Ruby中的here文档[n]
    • 原始字符串英语String literal#Raw strings变体,用给字符串文字前导一个r来指示。转义序列不被解释,因此在文字反斜杠常见的地方很有用,比如正则表达式Windows风格的路径。[o]可比较于C#中的“@-引用”。
  • Python允许连续出现和只用空白分隔(包括换行)的字符串文字(可能使用了不同的引用约定),它们被聚合成一个单一的更长的字符串[107][p]
  • Python拥有在列表上的数组索引数组分片英语array slicing表达式,表示为a[key]a[start:stop]a[start:stop:step]。索引是基于零的,负数是相对于结尾的。分片从“开始”(start)索引直到但不包括“停止”(stop)索引。分片的第三个参数叫做“步长”(step)或“间隔”(stride),允许元素被跳过和用负数指示反向。分片索引可以省略,例如a[:],这返回整个列表的一个复本。[q]分片的每个元素都是浅层复制英语Object copying的。

在Python中,在表达式和语句之间的区别是严格强制性的,对比于语言如Common LispSchemeRuby。这导致重复了某些功能。比如:列表推导式对当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(局部、包围、全局、内建)顺位规则。在函数中赋值一个变量将导致它成为这个函数的局部变量,就是说它的作用域在整个函数中,而不是在这个赋值之后至这个函数结束,因此在这个赋值之前引用它,不再于这个函数之外查找同名变量而是引发一个错误。缺省的名字解析规则可以用globalnonlocal关键字来覆盖。global声明的变量是全局变量。[t]global可以用于嵌套的函数中。嵌套函数中还可以使用nonlocal声明,用于赋值到给非局部变量英语Non-local variable[u]

Python可以指定形式参数的缺省值,在函数定义时于形式参数序列中以param=value样式进行一次性初始化。形式参数在初始化之后保持既有绑定,函数的后续调用可继续对它进行访问或变更。[v]在函数调用时为有缺省值的形式参数提供实际参数是可选的。Python支持位置实际参数和关键字实际参数。函数调用时,实际参数可以如同C语言那样按照位置与形式参数匹配;也可以采用命名参数英语Named parameter(或称为关键字实际参数),即kwarg=value样式的实际参数。使用不对应实际参数的特殊形式参数/*,可以将参数序列分为唯位置参数[108]、可位置可关键字参数和唯关键字参数三部份。有缺省值的形式参数之后不能跟随无缺省值的可位置形式参数。[w]在一个函数调用的实际参数序列中,关键字实际参数必须出现在位置实际参数之后。

在位置和关键字形式参数序列末尾可以分别有*args**kwargs这样的形式参数,它们对应于在函数调用时提供的,超出形式参数序列规定而无所对应的多个实际参数;在形式参数名字前加一个*号,该形式参数argstuple类型,对应可变数目的位置实际参数;在形式参数名字前加**号,该形式参数kwargsdict类型,对应可变数目的关键字实际参数。[x]在位置实际参数已经在一个序列类型如列表或元组的对象中的情况下,在引用它的变量前加一个*号传递给函数,则其中所有元素解包为多个位置实际参数,关键字实际参数在字典中则加**号来传递给函数。

修饰器(decorator)是用来修改一个函数、方法或类定义的任何可调用Python对象。将正被定义的最初对象传递给修饰器,它返回一个修改后的对象,接着把它绑定到在定义中那个名字。Python修饰器部份受到Java注解的影响,而有类似的语法;修饰器语法是纯粹的语法糖,使用@作为关键字形成修饰符。修饰器是一种形式的元编程,它们增强它们所修饰的函数或方法的行动。[y] 多个修饰器可以链接起来,通过在毗连的行上放置多个修饰符,或者使用中间变量。[z] 函数修饰器的正规用法包括:用来建立类方法静态方法[51],实现多方法,增加函数特性,跟踪英语Tracing (software),设置先决条件后置条件同步[109];此外更远大的用法包括:尾调用消除[110]记忆化甚至改进修饰器的写作[111]

为了增强代码的可读性,可以在函数后书写“文档字符串”(简称docstrings),用于解释函数的作用、参数的类型与意义、返回值类型与取值范围等。可以使用内置函数help()打印出函数的使用帮助。[aa]自从Python 3.5,开始支持类型提示[112],可以标注函数的参数与返回值[113]。此特性可方便IDE对源代码进行更深入的分析。[ab]

对象及其方法

Python支持大多数面向对象编程技术。在Python中所有东西都是对象,包括、函数、数和模块。它允许多态性,不只是在类层级英语Class hierarchy之内而且通过采用鸭子类型的方式。任何对象可以用于任何类型,只要它有适当的方法特性(attribute)就能工作。Python天然支持继承包括多重继承,为此采用C3线性化或方法解析次序(MRO)算法,还支持mixin。Python支持元类[114],它是增进类的功能的高级工具。

Python使用名字修饰有限的支持私有变量。对象的特性可以被提取为一个字典[115]。在Python中不强制使用访问子变异子方法来访问数据成员的面向对象编程信条。就像Python提供函数式编程构造但不尝试要求参照透明性英语referential transparency(无副作用)一样,它提供对象系统但不要求面向对象编程行为。

对象方法是附属于这个对象的的函数。对于正常的方法和函数,语法instance.method(arguments),是Class.method(instance, arguments)语法糖。Python的方法有显式的self英语this (computer programming)形式参数用来访问实例数据,对比于在其他一些面向对象编程语言(比如C++JavaObjective-CRuby)中隐式的selfthis英语this (computer programming)关键字[116]。在Python中,self可以被看作是一个习惯用法,它可以被换为任何其它合法的参数名。[ac]

Python支持一些以__开始和结束的特殊方法名,它们用于实现运算符重载和实现多种特殊功能[62]。在Python中,可以通过定义特殊方法来重载运算符,比如在一个类上定义__add__()将允许在这个类的实例上使用+算符。在Python中,当一个子类的方法覆盖超类方法的时候,通过调用super().method来调用与子类的self.method方法同名超类方法[117][ad]

Python允许通过使用@classmethod@staticmethod修饰符来分别建立类方法静态方法。给类方法的第一个实际参数是类对象而非对实例的self引用。静态方法没有特定的第一个实际参数,实例或类对象都不固定的传递给静态方法。[ae]

在Python中定义了一个或多个特殊方法__get__()__set__()__delete__()的类可以用作描述器(descriptor)[118]。如此建立一个描述器的实例作为另一个类的一个类成员,使得这个实例成为此另一个类的属性(property)。使用与特性(attribute)访问相同的语法,访问一个实例对象中的这个成员属性。[af] Python的property内建函数,将一个类中特殊定义的访问一个特性的那些方法包装成的这个类的一个属性[119][ag]

类型

 
Python 3中的标准类型层次结构

Python使用鸭子类型并拥有有类型的对象和无类型的变量名字。在编译期不检查类型约束,而宁愿在一个对象上的操作出现可能的失败,表现出这个给定对象不具有适合的类型。尽管是动态类型系统,Python却是强类型的,禁止没有明确定义的操作(比如加一个数到一个字符串),而不是默默的去尝试转换使其有意义。Python支持广泛的类型和类的内省。类型是type的实例,可以被读取和比较。

Python有着范围广泛的基本数据类型。同时具备常规的整数和浮点算术,它透明的支持任意精度算术复数十进制浮点数英语Decimal floating point。Python支持种类繁多的字符串操作。在Python中字符串是不可变的,所以在其他编程语言中可能就地改变字符串的字符串操作比如字符替换,在Python中返回新的字符串。

Python的一个非常有用方面就是搜集(或称容器)类型的概念。一般的说,搜集是以一种易于引用或索引的方式包含其他对象的对象。Python对建立容器类型的对象有着语法上的支持。[ah]搜集有二种基本形式:序列和映射。有次序的序列类型是列表(动态数组英语array data type)、元组和字符串。所有序列类型都是位置索引的(从0到长度−1),并且除了字符串,都可以包含任意类型的对象,在同一个序列中包括多种类型的对象。字符串和元组是不可变的,使得它们成为字典的键的完美候选者。在另一方面,列表是可变的,元素可以被插入、删除、修改、添加或就地排序。

在另一方面,映射是以“字典”形式实现的无次序的类型,它将一组不可变的键映射到相应的元素上(非常像数学函数)。在字典中的键必须是不可变的Python类型,比如整数或字符串,因为在底层它们是通过散列函数实现的。字典还是语言内部的中心,因为它们居于所有Python对象和类的核心:在变量名字(字符串)和这个名字所引用的值之间的映射就存储为字典,而这些字典可以通过对象的__dict__特性直接访问。

集合英语Set (abstract data type)搜集类型是在版本2.4中增加入语言核心的。集合是不包含重复项的无索引、无次序的搜集,并且实现了集合论运算比如并集交集相对补集对称差子集测试。有二种类型的集合:可变的set和不可变的frozenset。集合中元素必须是可散列的,比如说,frozenset可以是正规set的元素而反之不行。Python还提供了广泛的搜集操纵能力比如内建的包含元素检查和通用迭代协议

Python允许编程者使用定义自己的类型[48],类在面向对象编程中是最经常使用的。类的新实例是通过调用这个类的构造器而创建的,而类都是元类type的实例,typetype元类自身的实例,[ai]这允许了元编程反射

在版本3.0之前,Python有两种类:旧式的和新式的[120]。二种样式的语法是一样的,不同在于是否直接或间接的继承自类object,所有新式类都从object继承并且是type的实例。在Python 2系列2.2以上,二种类都可以使用[48]。在Python 3.0中淘汰了旧式类。

长期规划是支持渐进类型英语gradual typing[121],并且自从Python 3.5,语言的语法允许指定静态类型,但在缺省实现CPython中不检查它们。有实验的叫做“mypy”的可选的静态类型检查器支持编译期类型检查[122]

Python 3内置类型总结
类型 可变性 描述 语法例子
bool 不可变 布尔值 True
False
int 不可变 理论上无限制大小的整数[123] 42
float 不可变 双精度浮点数。精度是机器依赖的但实际上一般实现为64位IEEE 754数而带有53位的精度[124]

1.414

complex 不可变 複數,具有实部和虚部 3+2.7j
range 不可变 通常用在循环中的数的序列,规定在for循环中的次数[125] 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 可变 无序集合英语Set (abstract data type),不包含重复项;可以包含混合的类型,如果可散列的话 {4.0, 'string', True}
set()
frozenset 不可变 无序集合英语Set (abstract data type),不包含重复项;可以包含混合的类型,如果可散列的话 frozenset([4.0, 'string', True])
types.EllipsisType 不可变 省略号英语Ellipsis (programming operator)占位符,用作NumPy数组的索引 ...
Ellipsis
types.NoneType 不可变 表示值缺席的对象,在其他语言中经常叫做null None
types.NotImplementedType 不可变 可从重载运算符返回的占位符,用来指示未支持的运算数(operand)类型 NotImplemented

除了各种数据类型,Python解释器内建了还有很多其他类型,比如上下文管理器类型,模块、方法、代码对象、类型对象、内部对象等类型。

数学

Python的算术运算使用平常的符号+-*/下取整除法算符//模除%(这里的余数可以是负数,比如4 % -3 == -2)。它还有指数算符**,比如5**3 == 1259**0.5 == 3.0,和矩阵乘法算符@[98]。这些算符就像在传统数学中一样运算,具有同样的优先级规则中缀算符+-还可以分别表示取原数和取相反数一元算符。

在整数之间的除法/产生浮点数结果。除法/的表现随着版本不同而有着显著变化[126]

Python提供了round()函数用于把一个浮点数修约成最近的整数[127]

Python允许由比较运算链接起来的布尔表达式表现得如在数学中常用的一样。比如,表达式a < b < c测试a小于b并且b小于c[128]。C派生语言不一样的解释这个表达式:在C中,这个表达式将首先求值a < b,结果为01,接着把这个结果比较于c[129]

Python对所有整数运算使用任意精度算术。在decimal模块中的Decimal类型/类提供十进制浮点数到预定义的任意精度并有多种修约模式[130]。在fractions模块中的Fraction类提供任意精度的有理数[131]

由于Python有着广泛的数学库,除了求绝对值函数abs()列入内建函数之外,大多数数学函数处于mathcmath模块内。前者用于实数运算,而后者用于复数运算。[aj]特别是,第三方库NumPy进一步扩展了固有能力,Python经常被用作科学脚本语言来处理如数值数据处理和操纵等问题[132][133]

标准库

Python拥有一个强大的标准库[134]。Python语言的核心只包含数值、字符串、列表、字典、文件等常见类型和函数,而由Python标准库提供了系统管理、网络通信、文本处理、数据库接口、图形系统、XML处理等额外的功能。

Python标准库的主要功能有:

  • 文本处理英语Text processing,包含文本格式化、正则表达式、文本差异计算与合并、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直譯器[135]。Python属于动态语言,将Python程序编译成中间形式的字节码[136],并接着在它的虚拟机上执行[137],相较于C/C++等编译成机器码编译语言而言运行速度较慢[138]

主要实现
  • CPython:官方的直譯器,需要区别于其他直譯器的时候才以CPython称呼。
  • MicroPythonCircuitPython英语CircuitPython:它们是为微控制器而优化的Python 3变体。
  • Pyston:CPython 3.8.12的分叉,具有包括JIT的额外性能优化[139],还将其JIT部份作为扩展模块pyston_lite_autoload来单独发行[140]
  • Cinder:由Meta开源发布,它是Meta内部使用的面向性能的CPython 3.10分叉,具有包括JIT的很多优化[141]
  • PyPy:用RPython书写的Python实现,其主线版本兼容至CPython 3.8,测试版本兼容至CPython 3.9,它采用了跟踪JIT英语Tracing just-in-time compilation,缺省支持stackless模态。
  • Stackless Python:实现微线程英语microthread的CPython 3.8分叉,它不使用C内存堆栈,因而允许大规模并发程序。
到其他语言的交叉编译器
  • Cython:将扩充了静态类型的Python超集编译成CC++
  • Numba:使用LLVM,将包括很多NumPy函数的聚焦数值计算的Python子集,翻译成快速的机器码,它为在CPU和GPU上并行化Python代码提供了大量选项。
  • Pyjion:CPython的JIT扩展,它将Python代码编译成本机CIL,从而使用.NET CLR来执行它[142]
  • Nuitka英语Nuitka:用Python书写的到C11C++03优化编译器英语Optimizing compiler,它能建立不需单独的安装器就能运行的可执行程序[143]
  • Pythran:将聚焦于科学计算的Python子集编译成C++11提前编译器英语Ahead-of-time compilation,它能利用上多核SIMD指令单元[144]
  • MyHDL英语MyHDL:将Python编译成VHDL

仍在维护中的旧版本实现有:IronPython,它是面向.NETEcma 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英语PyScripter:功能较全的开源IDE,使用Delphi开发。
  • PyCharm:由JetBrains公司出品,具备一般IDE的功能,比如调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、单元测试、版本控制等等,另外,它还提供了一些功能用于Django开发,同时支持Google App Engine,还支持IronPython。它是商业软件,但也具有社区版和教育版。
  • Komodo英语Komodo IDEKomodo Edit英语Komodo Edit:后者是前者的免费精简版。
  • WingIDE英语WingIDE:商业软件,有免費的功能有限的Wing IDE 101,適用於入門者教學。

應用

 
Python Powered

在很多作業系統裡,Python是標準的系统元件。大多數Linux發行版macOS都集成了Python,可以在終端機下直接執行Python。雖然Python可被粗略地分類為腳本語言,Python的支持者較喜歡稱它為一種高階動態語言,常像“胶水”一样被用来连接软件组件,已经显著的区别于Unix shellWindows PowerShell这样的语言。基于Python的xonsh,是跨平台的、青睐Unix的shell语言命令行界面[145]

Python社群提供了大量的功能覆盖众多领域的第三方模組,其使用方式与标准库类似。第三方模块可以使用Python/Cython或者C编写。软件工具SWIGSIP英语SIP (software),通过定义接口文件或规定文件的方式,可以将C/C++编写的程序库包装为Python模块。Python解释器本身也可以被集成到其它需要腳本語言的程式内。

pip是事实标准和官网推荐的用Python书写的软件包管理系统[146],它通常连接到叫做Python包索引的一个公开软件包在线仓库。pipenv自动为用户项目建立和管理虚拟环境,还在安装/卸装软件包的时候,向Pipfile文件增加/移除这个软件包[147]。pyenv可以安装并轻易切换多个版本的Python[148]

自从2003年,Python始终排行于TIOBE编程社区索引英语TIOBE Programming Community Index前十最流行编程语言,在2021年10月它首次达到了第一名最流行语言(居于CJava之前)[149],并被选为2007年、2010年、2018年、2020年和2021年的年度编程语言[149]

網絡服务

Python定義了WSGI標準應用接口来協調Http伺服器與基於Python的Web程式之間的溝通。比如,通過mod_wsgi英语mod_wsgi模組,Apache可以運行用Python編寫的Web程式。Zope是著名的用Python编写的开源的Web应用服务器Tornado是用Python语言写成的非阻塞式web服务器,也是轻量级的Web框架。

Python對於各种網路協定的支援很完善,因此經常被用於編寫伺服器軟體、網路爬蟲等Web開發。用Python编写的一些Web框架,可以讓程式設計師輕鬆地開發和管理複雜的Web程式。著名的第三方Web框架和函数库:

  • Django:MTV架构[150]的Web开发框架,注重组件的重用性和“可插拔性”、快速开发DRY法则
  • web2py:MVC架构的全栈Web框架,聚焦于快速开发,偏好约定优于配置方式。
  • TurboGears:MVC架构的混合Web框架,可以担任全栈框架或微框架二者。
  • Pyramid:极简主义的Web框架,不预定持久化方式,它是Pylons计划的一部分。
  • Flask:微Web框架,不要求特定的工具或库。
  • aiohttp:轻量级的Web框架[151],采用的是Python3的asyncio异步特性。
  • Twisted事件驱动的网络编程框架。它支援多數標準的網路協定(包含客户端和伺服器),並且提供了多種工具,被廣泛用於編寫高性能的伺服器軟體。
  • Requests:适合于常人使用的HTTP库,封装了许多繁琐的HTTP功能,极大地简化了HTTP请求所需要的代码量。
  • Beautiful Soup:用来解析HTML/XML的一个简单易用Python包。
  • gevent:是基于协程的高性能并发网络编程库[152],使用greenlet在libevlibuv之上提供了高层的同步式API。

图形用户界面

Python本身包含了Tkinter库,它是Python的业界标准GUI并被集成进入了IDLE。Tkinter基于了Tcl命令工具,能够支持简单的GUI开发。但是越来越多的Python程序员选择第三方GUI套件来开发跨平台的桌面软件,使用它们开发的桌面软件运行速度快,与用户的桌面环境相契合。著名的第三方GUI库:

  • PyQtQt的Python绑定库,由Riverbank Computing公司自从1998年发行,采用GPL许可证或商业许可证。
  • PySideQt的Python绑定库,由Qt公司自从2009年发行,采用LGPL许可证。
  • PyGObject:替代了PyGTK,为Python程序访问基于GObject的库提供了包装库,GObject是GTKGIO英语GIO (software)GStreamer等库使用的对象系统。
  • Kivy:用于开发多点触控应用软件的开源Python库,采用了自然用户界面(NUI)。
  • WxPython:GUI编程框架wxWidgets的Python包装库,它与MFC的架构相似。
  • PySimpleGUI:将Tkinter、Qt、WxPython和Remi[153]的GUI框架变换成简单的接口[154]
  • Gooey:将几乎所有Python 3控制台程序用一行代码转变成GUI应用[155]
  • Pyforms:开发能够在三种不同环境即桌面GUI、终端和网页下执行的程序的Python框架[156]

数据科学

重要的数据科学用第三方软件库有:

其它种类的库

应用软件

有一些Linux發行版的安裝器使用Python語言編寫。在RPM系列Linux发行版中,有一些系统组件就是用Python编写的。一些著名的互联网公司在内部使用Python[141]。一些遊戲比如EVE,使用Python編寫遊戲的邏輯、伺服器。如下著名应用使用Python编写或将它作为嵌入式脚本:

社群流行

  • PyCon:各地社群舉辦的會議,通常每年舉辦。各社群在會議中討論Python相關的議題。
  • Python Discord:参与者众多的Python社区[195]
  • PyLadies英语PyLadies:由女性社群發起的社群,主要注重於發展Python的女性程式設計社群。
  • Django Girls英语Django Girls:使用Django網頁設計框架,推廣使用Python進行網頁設計的技術。

影響的语言

Python的设计和哲学已经影响了很多其他编程语言:

  • Boo:使用了缩进、类似的语法和类似的对象模型[196]
  • Cobra英语Cobra (programming language):使用了缩进和类似的语言,而且它的致谢文档将Python列为影响它的首要语言[197]
  • CoffeeScript:是交叉编译至JavaScript的编程语言,有受Python启发的语法。
  • ECMAScript/JavaScript:从Python借鉴了迭代器生成器[198]
  • GDScript:是非常类似Python的脚本语言,内置入了Godot游戏引擎[199]
  • Genie:基于Vala编译器的具有近似Python语法的一种语言。
  • Go:设计为“有动态语言如Python的工作速度”[200],并共享了相同的分片数组的语法。
  • Groovy:受到Python等动态类型语言的影响[201]
  • Nim:使用缩进和类似的语法[202]
  • Swift:是Apple开发的编程语言,有受Python启发的语法[203]

Ruby的创建者松本行弘曾说过:“我想要一种脚本语言,比Perl更加强力而且比Python更加面向对象,因此我决定设计自己的语言”[204]Julia设计原则中有一条是:“像Python一样可用于通用编程”[25]

代码示例

  1. ^ 縮排示例:
    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, } 
  2. ^ 采用了并行赋值的斐波那契数列函数示例:
    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() 
  3. ^ 产生素数的惰性生成器的示例:
    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)) 
  4. ^ 遵循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() 
  5. ^ 使用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("文件写入完全成功") 
  6. ^ 用生成器模拟协程示例:
    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 
  7. ^ 原生的协程示例:
    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()) 
  8. ^ 列表的推导式示例。比如:
    >>> [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])) 
  9. ^ 生成器表达式示例。比如:
    >>> 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} 
  10. ^ 字典推导式{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} 
  11. ^ 匿名函数示例:
    >>> 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). 

  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} 
  13. ^ 格式化字符串的示例,例如下列命令行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}) 
  14. ^ 多行字符串文字带有字符串插值英语String interpolation(使用了format方法)的示例:
    print("""亲爱的{recipient}, 我希望你离开Sunnydale并永不返回. 不是很爱你的, {sender} """.format(sender="吸血鬼猎人Buffy", recipient="Spike")) 
  15. ^ 原始字符串的示例:
    >>> # 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)' >>> # 注意如果实际参数中有圆括号或逗号则上例无效。 
  16. ^ 字符串文字串接示例:
    >>> title = "SICP in Python"" - " \ ...  'CS61A: Online Textbook' 

    等价于:

    >>> title = "SICP in Python - CS61A: Online Textbook" 
  17. ^ 下面几个判断语句为真,表示列表分片结果符合预期:
    >>> 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 
  18. ^ 词法闭包的例子:
    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)是个闭包。 
  19. ^ 函数的形实参数二者结合示例。例如:
    >>> 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 
  20. ^ 局部变量和全局变量示例:
    >>> 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 
  21. ^ 非局部变量示例:
    >>> 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 
  22. ^ 函数的形式参数缺省值的持久性示例:
    >>> def f(a, L=[]): ...  L.append(a) ...  return L ...  >>> print(f(1)) [1] >>> print(f(2)) [1, 2] >>> print(f(3)) [1, 2, 3] 
  23. ^ 函数的形式参数缺省值的定义示例:
    >>> 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={}) 
  24. ^ 函数的可变参数的定义示例:
    >>> 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={}) 
  25. ^ 定义修饰器的示例:
    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 
  26. ^ 修饰器工厂示例,这里的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 (Monty Python)()结果为:

    >>> black_knight() I'm invincible! My favourite colour is blue. None shall pass. 
  27. ^ 调用函数使用帮助信息示例。比如:
    >>> 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. 
  28. ^ 如下这样给参数增加类型标注的提示信息:
    def send_mail(from: str, to: str, title: str, body: str) -> bool: pass 
  29. ^ 对象的方法示例:
    >>> 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! 
  30. ^ 特殊方法和子类调用超类方法的例子:
    >>> 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() 我觉得我在平行宇宙中把车停歪了. 
  31. ^ 特殊方法、类方法和静态方法(__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 
  32. ^ 在类中采用数据描述器的示例:
    >>> 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} 
  33. ^ 在类中调用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__'} 
  34. ^ 建立列表的特殊语法示例:
    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: []} 
  35. ^ 两个类及元类等的实例关系(蓝色连接)与继承关系(绿色连接)示意图:
     
    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'> () 
  36. ^ 数学运算示例。比如:
    >>> def mean(seq): ...  return sum(seq) / len(seq) ...  >>> mean([3, 4]) 3.5 >>> import math >>> print(math.sin(math.pi/2)) 1.0 

註釋

  1. ^ 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. ^ 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. ^ . wiki.python.org. [2021-01-27]. (原始内容存档于2021-03-14). 
  4. ^ PEP 483 -- The Theory of Type Hints. Python.org. [2020-04-22]. (原始内容于2020-06-14). 
  5. ^ File extension .pyo was removed in Python 3.5. See PEP 0488 (页面存档备份,存于互联网档案馆
  6. ^ Holth, Moore. PEP 0441 -- Improving Python ZIP Application Support. 2014-03-30 [2015-11-12]. (原始内容于2018-12-26). 
  7. ^ . [2022-03-04]. (原始内容存档于2022-04-24). 
  8. ^ . [25 May 2019]. (原始内容存档于2020-06-15). 
  9. ^ 9.0 9.1 9.2 Why was Python created in the first place?. Python FAQ. [2007-03-22]. (原始内容于2008-02-23). 
  10. ^ . [2021-03-14]. (原始内容存档于2019-10-22). 
  11. ^ Kuchling, Andrew M. . amk.ca. 22 December 2006 [12 March 2012]. (原始内容存档于1 May 2007). 
  12. ^ 12.0 12.1 . docs.python.org. [2020-04-22]. (原始内容存档于2020-06-14). 
  13. ^ van Rossum, Guido. . 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. 
  14. ^ 14.0 14.1 . 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 
  15. ^ Lundh, Fredrik. . 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. 
  16. ^ Simionato, Michele. . 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 
  17. ^ Kuchling, A. M. . Python v2.7.2 documentation. Python Software Foundation. [9 February 2012]. (原始内容存档于2012-10-24). 
  18. ^ Schemenauer, Neil; Peters, Tim; Hetland, Magnus Lie. . Python Enhancement Proposals. Python Software Foundation. 18 May 2001 [9 February 2012]. (原始内容存档于2020-06-05). 
  19. ^ Smith, Kevin D.; Jewett, Jim J.; Montanaro, Skip; Baxter, Anthony. . Python Enhancement Proposals. Python Software Foundation. 2 September 2004 [24 February 2012]. (原始内容存档于2020-06-03). 
  20. ^ . Python 3 documentation. Python Software Foundation. [24 July 2015]. (原始内容存档于2016-06-04). 
  21. ^ . coffeescript.org. [2021-03-14]. (原始内容存档于2020-06-12). 
  22. ^ . [28 February 2020]. (原始内容存档于2020-06-01). 
  23. ^ . www.2ality.com. 24 February 2013 [15 May 2015]. (原始内容存档于2018-12-26). 
  24. ^ Rauschmayer, Axel. . O'Reilly, Speaking JavaScript. [15 May 2015]. (原始内容存档于2018-12-26). 
  25. ^ 25.0 25.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 [...] 
  26. ^ Ring Team. . ring-lang.net. ring-lang. 4 December 2017 [2021-03-14]. (原始内容存档于2018-12-25). 
  27. ^ 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. 
  28. ^ Lattner, Chris. . 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. 
  29. ^ 彼德·諾米格. 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). 
  30. ^ 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). 
  31. ^ 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). 
  32. ^ Stack Overflow Developer Survey 2020. Stack Overflow. [2021-03-05]. (原始内容于2 March 2021). 
  33. ^ The State of Developer Ecosystem in 2020 Infographic. JetBrains: Developer Tools for Professionals and Teams. [2021-03-05]. (原始内容于1 March 2021) (英语). 
  34. ^ 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. 
  35. ^ PYPL PopularitY of Programming Language index. pypl.github.io. [2021-03-26]. (原始内容于14 March 2017) (英语). 
  36. ^ Guido van Rossum - Resume. 
  37. ^ Whetting Your Appetite. The Python Tutorial. Python Software Foundation. [2012-02-20]. (原始内容于2012-10-26). 
  38. ^ . Linux Format. 2005-02-01 [2007-11-01]. (原始内容存档于2006-10-01). 
  39. ^ Transfer of power. [2020-11-29]. (原始内容于2018-07-12). 
  40. ^ PEP 8100. python. Python Software Foundation. [2019-05-04]. (原始内容于2020-06-04). 
  41. ^ Steering Council nomination: Guido van Rossum (2020 term). [2020-10-11]. (原始内容于2019-12-29). 
  42. ^ HISTORY. Python source distribution. Python Foundation. [2017-11-23]. (原始内容于2017-12-01). 
  43. ^ The Making of Python. Artima Developer. [2007-03-22]. (原始内容于2016-09-01). 
  44. ^ van Rossum, Guido. The fate of reduce() in Python 3000. Artima Developer. [2007-03-22]. (原始内容于2007-04-07). 
  45. ^ . [2007-04-29]. (原始内容存档于2007-05-01). 
  46. ^ Kuchling, A. M.; Zadka, Moshe. What's New in Python 2.0. Python Software Foundation. 2000-10-16 [2012-02-11]. (原始内容于2012-10-23). 
  47. ^ Hylton, Jeremy. PEP 227 -- Statically Nested Scopes. 2000-11-01 [2007-03-22]. (原始内容于2007-03-29). 
  48. ^ 48.0 48.1 48.2 Guido van Rossum. Unifying types and classes in Python 2.2. [2020-09-26]. (原始内容于2019-09-28). 
  49. ^ What’s New in Python 2.2 - PEP 234: Iterators. [2020-10-21]. (原始内容于2021-02-07). 
  50. ^ . [2020-10-21]. (原始内容存档于2021-02-07). 
  51. ^ 51.0 51.1 What’s New in Python 2.2 - Descriptors. [2020-10-21]. (原始内容于2021-02-07). 
  52. ^ What’s New in Python 2.4 - PEP 318: Decorators for Functions and Methods. [2020-10-21]. (原始内容于2021-02-07). 
  53. ^ What’s New in Python 2.5 - PEP 343: The ‘with’ statement. [2020-10-21]. (原始内容于2021-02-07). 
  54. ^ . Python Software Foundation. [2009-07-08]. (原始内容存档于2020-06-14). 
  55. ^ Automated Python 2 to 3 code translation — Python Documentation. [2018-02-11]. (原始内容于2020-06-04). 
  56. ^ van Rossum, Guido. PEP 3000 – Python 3000. Python Enhancement Proposals. Python Software Foundation. 2006-04-05 [2009-06-27]. (原始内容于2016-03-03). 
  57. ^ PEP 373 -- Python 2.7 Release Schedule. python.org. [2017-01-09]. (原始内容于2020-05-19). 
  58. ^ PEP 466 -- Network Security Enhancements for Python 2.7.x. python.org. [2017-01-09]. (原始内容于2020-06-04). 
  59. ^ . [2022-03-25]. (原始内容存档于2022-04-13). 
  60. ^ Python Developer's Guide — Status of Python Version. devguide.python.org. [2022-08-26]. (原始内容于2022-08-26). 
  61. ^ PEP 8104 – 2023 Term Steering Council election. Python Software Foundation. 
  62. ^ 62.0 62.1 The Python Language Reference, section 3.3. Special method names. [2020-09-25]. (原始内容于2012-10-26). 
  63. ^ . [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. 
  64. ^ PEP 316 -- Programming by Contract for Python. [2021-01-17]. (原始内容于2021-01-22). 
    • . [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. 
  65. ^ PyDatalog. [2012-07-22]. (原始内容于2020-06-13). 
  66. ^ Extending and Embedding the Python Interpreter: Reference Counts. Docs.python.org. [2020-06-05]. (原始内容于2012-10-18) (英语). Since Python makes heavy use of malloc() and free(), it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called reference counting. 
  67. ^ Functional Programming HOWTO. [2020-09-26]. (原始内容于2012-10-24). 
  68. ^ 68.0 68.1 Hettinger, Raymond. PEP 289 – Generator Expressions. Python Enhancement Proposals. Python Software Foundation. 2002-01-30 [2012-02-19]. (原始内容于2020-06-14). 
  69. ^ Functional Programming Modules. Docs.python.org. [2020-09-26]. (原始内容于2020-09-20). 
  70. ^ Guido van Rossum. Foreword for "Programming Python" (1st ed.). 1996-05-01 [2020-09-12]. (原始内容于2014-07-24) (英语). 
  71. ^ . [2022-01-14]. (原始内容存档于2022-04-27). 
  72. ^ PEP 523 – Adding a frame evaluation API to CPython. [2022-08-29]. (原始内容于2022-08-29). 
  73. ^ Style Guide for Python Code: indentation. [2020-09-26]. (原始内容于2018-07-13). 
  74. ^ 2. Lexical analysis. Python v3.8.6 documentation. Docs.python.org. [2020-09-26]. (原始内容于2018-01-09). 
  75. ^ 2. Lexical analysis. Python v2.7.18 documentation. Docs.python.org. [2020-09-26]. (原始内容于2019-05-08). 
  76. ^ New Keywords. Python v3.5 documentation. Docs.python.org. [2016-06-01]. (原始内容于2016-06-18). 
  77. ^ Naming Conventions. [2017-10-06]. (原始内容于2018-07-13). 
  78. ^ 78.0 78.1 9.6. Private Variables. [2020-09-27]. (原始内容于2012-10-23). 
  79. ^ 79.0 79.1 PEP 342 -- Coroutines via Enhanced Generators. [2019-11-21]. (原始内容于2020-05-29). 
  80. ^ PEP 380 -- Syntax for Delegating to a Subgenerator. [2019-11-21]. (原始内容于2020-06-04). 
  81. ^ Highlights: Python 2.5. Python.org. [2020-09-21]. (原始内容于2019-08-04). 
  82. ^ 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). 
  83. ^ "It is Easier to Ask for Forgiveness than Permission" EAFP (页面存档备份,存于互联网档案馆), Python Glossary
  84. ^ Alex Martelli. . : 134 [2020-09-26]. (原始内容存档于2022-05-13). 
  85. ^ The "with" Statement. [2020-09-26]. (原始内容于2014-12-14). 
  86. ^ 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). 
  87. ^ Thomas Baruchel. . [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. 
  88. ^ PEP 3156 -- Asynchronous IO Support Rebooted: the "asyncio" Module. [2019-11-21]. (原始内容于2019-11-14). 
  89. ^ 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. 
  90. ^ PEP 492 -- Coroutines with async and await syntax. [2019-11-21]. (原始内容于2019-01-05). 
  91. ^ What’s New In Python 3.7. [2019-11-21]. (原始内容于2019-11-28). 
  92. ^ 92.0 92.1 92.2 Python.org: Modules. [2020-10-30]. (原始内容于2021-02-06). 
  93. ^ 93.0 93.1 Python.org: The import Statement. [2020-10-30]. (原始内容于2021-02-07). 
  94. ^ Python.org: __main__. [2020-10-30]. (原始内容于2021-02-07). 
  95. ^ Python.org: Dir(). [2020-09-25]. (原始内容于2018-10-26). 
  96. ^ division. python.org. [2014-10-17]. (原始内容于2006-07-20). 
  97. ^ Python 3.5.1 Release and Changelog. python.org. [2016-01-01]. (原始内容于2020-05-14). 
  98. ^ 98.0 98.1 PEP 0465 -- A dedicated infix operator for matrix multiplication. python.org. [2016-01-01]. (原始内容于2020-06-04). 
  99. ^ . [2022-01-18]. (原始内容存档于2022-04-10). 
  100. ^ Chapter 15. Expressions - 15.21.1. Numerical Equality Operators == and !=. Oracle Corporation. [2016-08-28]. (原始内容于2020-06-07). 
  101. ^ Chapter 15. Expressions - 15.21.3. Reference Equality Operators == and !=. Oracle Corporation. [2016-08-28]. (原始内容于2020-06-07). 
  102. ^ What’s New in Python 3.8 - Assignment expressions. [2019-10-14]. (原始内容于2020-06-08). 
  103. ^ What’s New in Python 3.9 - Dictionary Merge & Update Operators. [2021-06-12]. (原始内容于2020-10-07). 
  104. ^ 4. Built-in Types — Python 3.6.3rc1 documentation. python.org. [2017-10-01]. (原始内容于2020-06-14). 
  105. ^ 5.3. Tuples and Sequences — Python 3.7.1rc2 documentation. python.org. [2018-10-17]. (原始内容于2020-06-10). 
  106. ^ 106.0 106.1 PEP 498 -- Literal String Interpolation. python.org. [2017-03-08]. (原始内容于2020-06-15). 
  107. ^ 2. Lexical analysis. Python v2.7.5 documentation. Docs.python.org. [2013-08-16]. (原始内容于2012-10-23). 
  108. ^ . [2020-09-24]. (原始内容存档于2020-06-08). 
  109. ^ Python 2.4 Decorators: Reducing code duplication and consolidating knowledge. Dr. Dobb's. 2005-05-01 [2007-02-08]. (原始内容于2007-02-06). 
  110. ^ New Tail Recursion Decorator. ASPN: Python Cookbook. 2006-11-14 [2007-02-08]. (原始内容于2007-02-09). 
  111. ^ The decorator module. [2007-02-08]. (原始内容于2007-02-10). 
  112. ^ . [2021-03-01]. (原始内容存档于2021-02-09). 
  113. ^ . [2021-03-01]. (原始内容存档于2015-01-06). 
  114. ^ The Cain Gang Ltd. (PDF). [2009-06-27]. (原始内容 (PDF)存档于2009-05-30). 
  115. ^ Special Attributes. [2020-09-12]. (原始内容于2020-06-14). 
  116. ^ Why must 'self' be used explicitly in method definitions and calls?. Design and History FAQ. Python Software Foundation. [2012-02-19]. (原始内容于2012-10-24). 
  117. ^ super().method, in Python 3. [2020-09-25]. (原始内容于2018-10-26). 
  118. ^ Descriptor HowTo Guide. [2020-09-26]. (原始内容于2020-09-18). 
  119. ^ Built-in Functions: property. [2020-09-25]. (原始内容于2018-10-26). 
  120. ^ The Python Language Reference, section 3.3. New-style and classic classes, for release 2.7.18. [2020-09-25]. (原始内容于2020-05-05). 
  121. ^ Type hinting for Python. LWN.net. 2014-12-24 [2015-05-05]. (原始内容于2019-06-20). 
  122. ^ mypy - Optional Static Typing for Python. [2017-01-28]. (原始内容于2020-06-06). 
  123. ^ 。实际受限于机器的内存大小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). 
  124. ^ 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 
  125. ^ Built-in Types. [2019-10-03]. (原始内容于2020-06-14). 
  126. ^ 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). 
  127. ^ round, The Python standard library, release 3.2, §2: Built-in functions, [2011-08-14], (原始内容于2012-10-25) 
  128. ^ Beazley, David M. Python Essential Reference 4th. 2009: 66. 
  129. ^ Kernighan, Brian W.; Ritchie, Dennis M. The C Programming Language 2nd. 1988: 206. 
  130. ^ Batista, Facundo. PEP 0327 -- Decimal Data Type. Python.org. [2015-09-26]. (原始内容于2020-06-04). 
  131. ^ What's New in Python 2.6 — Python v2.6.9 documentation. docs.python.org. [2015-09-26]. (原始内容于2019-12-23). 
  132. ^ 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). 
  133. ^ Shell, Scott. An introduction to Python for scientific computing (PDF). 2014-06-17 [2019-02-03]. (原始内容 (PDF)于2019-02-04). 
  134. ^ Przemyslaw Piotrowski, Build a Rapid Web Development Environment for Python Server Pages and Oracle (页面存档备份,存于互联网档案馆), Oracle Technology Network, July 2006. Accessed October 21, 2008.
  135. ^ Python Interpreters Benchmarks. [2022-08-30]. (原始内容于2022-08-20). 
  136. ^ CPython byte code. Docs.python.org. [2016-02-16]. (原始内容于2020-06-05). 
  137. ^ Python 2.5 internals (PDF). [2011-04-19]. (原始内容 (PDF)于2012-08-06). 
  138. ^ The Computer Language Benchmarks Game. [2020-04-30]. (原始内容于2020-06-14). 
  139. ^ Pyston - A faster and highly-compatible implementation of the Python programming language. [2022-08-29]. (原始内容于2022-08-29). 
  140. ^ Announcing Pyston-lite: our Python JIT as an extension module. [2022-08-29]. (原始内容于2022-08-29). This current release only supports Python 3.8, but since Pyston-lite has a much smaller surface area we believe we can target multiple releases, unlike Pyston which will only target a single release for the foreseeable future. 
  141. ^ 141.0 141.1 Cinder is Meta's internal performance-oriented production version of CPython. [2022-08-26]. (原始内容于2021-05-04). 
  142. ^ Pyjion - A JIT for Python based upon CoreCLR. [2022-08-29]. (原始内容于2022-08-29). 
  143. ^ Nuitka the Python Compiler. [2020-09-26]. (原始内容于2022-09-03). 
  144. ^ Pythran - Ahead of Time compiler for numeric kernels. [2022-08-29]. (原始内容于2022-08-29). 
  145. ^ XONSH is a Python-powered shell. [2022-08-28]. (原始内容于2022-09-03). 
  146. ^ Tool recommendations. python.org. [21 April 2022]. (原始内容于2022-09-06) (英语). 
  147. ^ Pipenv: Python Development Workflow for Humans. [2022-08-29]. (原始内容于2019-11-17). 
  148. ^ pyenv - Simple Python version management. [2022-08-30]. (原始内容于2022-09-08). 
  149. ^ 149.0 149.1 TIOBE Index. TIOBE - The Software Quality Company. [2021-10-06]. (原始内容于2020-06-14). 
  150. ^ 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). 
  151. ^ Asynchronous HTTP Client/Server for asyncio and Python. [2021-01-14]. (原始内容于2021-01-15). 
  152. ^ . [2021-03-13]. (原始内容存档于2021-06-07). 
  153. ^ Remi - Python REMote Interface library. [2022-08-28]. (原始内容于2022-08-28). 
  154. ^ PySimpleGUI - Python GUIs for Humans. [2022-08-28]. (原始内容于2022-08-28). 
  155. ^ Gooey - Turn (almost) any Python command line program into a full GUI application with one line. [2022-08-28]. (原始内容于2022-08-28). 
  156. ^ Pyforms - Python layer of Windows forms, based on PyQt and OpenGL. [2022-08-28]. (原始内容于2022-08-28). 
  157. ^ CuPy: NumPy & SciPy for GPU. [2022-08-31]. (原始内容于2022-08-31). 
  158. ^ 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. 
  159. ^ Dask - Parallel computing with task scheduling. [2022-08-31]. (原始内容于2022-08-31). 
  160. ^ Joblib: running Python functions as pipeline jobs. 
  161. ^ Thread-pool Controls. 
  162. ^ Plotly.js - Open-source JavaScript charting library behind Plotly and Dash. 
  163. ^ Dash - Analytical Web Apps for Python, R, Julia, and Jupyter. 
  164. ^ Streamlit — The fastest way to build data apps in Python. 
  165. ^ Panel - A high-level app and dashboarding solution for Python. 
  166. ^ Voilà - Voilà turns Jupyter notebooks into standalone web applications. 
  167. ^ Dashboarding tools. 
  168. ^ TensorFlow API Documentation - Module: tf. [2022-08-31]. (原始内容于2022-09-05). 
  169. ^ TensorFlow API Documentation - Module: tf.keras. [2022-08-31]. (原始内容于2020-01-22). 
  170. ^ SciKeras - Scikit-Learn API wrapper for Keras. [2022-09-01]. (原始内容于2022-06-19). 
  171. ^ skorch - A scikit-learn compatible neural network library that wraps PyTorch. [2022-09-01]. (原始内容于2022-08-24). 
  172. ^ JAX - Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more. [2022-08-28]. (原始内容于2021-02-05). 
  173. ^ Autograd - Efficiently computes derivatives of numpy code. [2022-08-28]. (原始内容于2022-07-18). 
  174. ^ XLA: Optimizing Compiler for Machine Learning. [2022-08-28]. (原始内容于2022-09-01). 
  175. ^ Flax is a neural network library for JAX that is designed for flexibility. [2022-08-31]. (原始内容于2022-09-03). 
  176. ^ NumPyro - Probabilistic programming with NumPy powered by JAX for autograd and JIT compilation to GPU/TPU/CPU. [2022-08-31]. (原始内容于2022-08-31). 
  177. ^ Brax - Massively parallel rigidbody physics simulation on accelerator hardware. [2022-08-31]. (原始内容于2022-08-31). 
  178. ^ Ray - Effortlessly scale your most complex workloads. 
  179. ^ Mars is a tensor-based unified framework for large-scale data computation which scales numpy, pandas, scikit-learn and Python functions. 
  180. ^ . [December 8, 2013]. (原始内容存档于2016-04-27). 
  181. ^ PyOpenGL is the most common cross platform Python binding to OpenGL and related APIs. [2022-01-07]. (原始内容于2011-06-15). 
  182. ^ . [2022-01-07]. (原始内容存档于2022-04-15). 
  183. ^ VisPy - interactive scientific visualization in Python. [2022-08-30]. (原始内容于2022-07-13). 
  184. ^ CUDA Python Manual. [2022-08-30]. (原始内容于2022-08-30). 
  185. ^ PyCUDA gives you easy, Pythonic access to Nvidia’s CUDA parallel computation API. [2022-05-29]. (原始内容于2022-06-28). 
  186. ^ . [2021-07-29]. (原始内容存档于2022-03-08). 
  187. ^ Kornia - Open Source Differentiable Computer Vision Library. 
  188. ^ . [2022-02-16]. (原始内容存档于2019-03-12). 
  189. ^ pythonnet - Python.NET. [2022-08-30]. (原始内容于2022-09-01). 
  190. ^ Fabric - Pythonic remote execution. [2013-04-08]. (原始内容于2014-04-11). 
  191. ^ Prefect - The easiest way to coordinate your dataflow. 
  192. ^ . [2021-03-13]. (原始内容存档于2021-06-07). 
  193. ^ 4.0 New Features and Fixes. LibreOffice.org. The Document Foundation. 2013 [25 February 2013]. (原始内容于9 February 2014). 
  194. ^ Panda3D Manual. [2022-09-04]. (原始内容于2018-12-29). 
  195. ^ Python Discord is a large community focused around the Python programming language. [2021-01-13]. (原始内容于2021-02-01). 
  196. ^ . boo.codehaus.org. Codehaus Foundation. [2008-11-24]. (原始内容存档于2008-12-11). 
  197. ^ Esterbrook, Charles. Acknowledgements. cobra-language.com. Cobra Language. [2010-04-07]. (原始内容于2008-02-08). 
  198. ^ . wiki.ecmascript.org. [2008-11-24]. (原始内容存档于2007-10-20). 
  199. ^ FAQ: What is GDScript and why should I use it?. [2020-09-13]. (原始内容于2020-05-19). 
  200. ^ Kincaid, Jason. Google's Go: A New Programming Language That's Python Meets C++. TechCrunch. 2009-11-10 [2010-01-29]. (原始内容于2010-01-18). 
  201. ^ Strachan, James. . 2003-08-29 [2007-06-11]. (原始内容存档于2007-04-05). 
  202. ^ 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). 
  203. ^ 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. 
  204. ^ . 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. 

参閲

外部連接

python, 关于与, 標題相近或相同的条目, 請見, 消歧義, 英國發音, ˈpaɪθən, 美國發音, ˈpaɪθɑːn, 是一种广泛使用的解释型, 高级和通用的编程语言, 支持多种编程范型, 包括函数式, 指令式, 反射式, 结构化和面向对象编程, 它拥有动态类型系统和垃圾回收功能, 能够自动管理内存使用, 并且其本身拥有一个巨大而广泛的标准库, 它的语言结构以及面向对象的方法, 旨在帮助程序员为小型的和大型的项目编写逻辑清晰的代码, 编程范型多范型, 函数式, 指令式, 反射式, 结构化, 面向对象設計者. 关于与 Python 標題相近或相同的条目 請見 Python 消歧義 Python 英國發音 ˈpaɪ8en 美國發音 ˈpaɪ8ɑːn 是一种广泛使用的解释型 高级和通用的编程语言 Python支持多种编程范型 包括函数式 指令式 反射式 结构化和面向对象编程 它拥有动态类型系统和垃圾回收功能 能够自动管理内存使用 并且其本身拥有一个巨大而广泛的标准库 它的语言结构以及面向对象的方法 旨在帮助程序员为小型的和大型的项目编写逻辑清晰的代码 Python编程范型多范型 函数式 指令式 反射式 结构化 面向对象設計者吉多 范罗苏姆實作者Python软件基金会发行时间1991年 32年前 1991 1 穩定版本3 11 1 2 2022年12月6日 32天前 預覽版本3 12 0a3 2 2022年12月6日 32天前 型態系統鸭子类型 动态 强类型 3 渐进 英语 gradual typing 自从3 5 4 作業系統跨平臺 Windows Linux Unix macOS等許可證Python软件基金会许可证文件扩展名 py pyi pyc pyd pyo 3 5之前 5 pyw pyz 自从3 5 6 網站www wbr python wbr org主要實作產品CPython PyPy IronPython Jython Stackless Python MicroPython CircuitPython 英语 CircuitPython RustPython 7 衍生副語言Cython RPython Starlark 英语 Bazel software 8 啟發語言ABC 9 Ada 10 ALGOL 68 11 APL 12 C 13 C 14 CLU 15 Dylan 16 Haskell 17 Icon 18 Java 19 Lisp 20 Modula 3 14 Perl Standard ML 12 影響語言Boo Cobra 英语 Cobra programming language CoffeeScript 21 D F Falcon Genie 22 Go Groovy JavaScript 23 24 Julia 25 Nim Ring 26 Ruby 27 Swift 28 維基教科書中有關zh Python的文本吉多 范罗苏姆于1980年代后期开始研发Python 作为ABC语言的后继者 它也可以被视为采用了叫做M 表达式 英语 M expression 的中缀表示法的一种LISP方言 29 吉多 范罗苏姆于1991年首次发布 Python 0 9 0 30 Python 2 0于2000 年发布并引入了新功能 Python 3 0于2008年发布 它是该语言的主要修订版 并非完全向后兼容 Python 2于2020年随2 7 18版停止支持 31 Python的设计哲学 强调代码的可读性和简洁的语法 尤其是使用空格缩进来划分代码块 相比於C或Java Python让开发者能够用更少的代码表达想法 Python解释器本身几乎可以在所有的操作系统中运行 它的官方直譯器CPython是用C语言编写的 Python是一個由社群驱动的自由软件 目前由Python软件基金会管理 Python是最受欢迎的编程语言之一 32 33 34 35 目录 1 歷史 2 特徵與設計哲學 3 語法 3 1 縮排 3 2 关键字 3 3 标识符 3 4 語句和控制流 3 5 表达式 3 6 函数 3 7 对象及其方法 3 8 类型 3 9 数学 4 标准库 5 程序代码实例 6 实现 7 开发环境 7 1 通用文本编辑器 7 2 专用开发环境 8 應用 8 1 網絡服务 8 2 图形用户界面 8 3 数据科学 8 4 其它种类的库 8 5 应用软件 8 6 社群流行 9 影響的语言 10 代码示例 11 註釋 12 延伸閱讀 13 参閲 14 外部連接歷史 编辑主条目 Python的歷史 Python創始人吉多 范羅蘇姆在2006年的照片 Python的創始人吉多 范羅蘇姆 在1982年至1995年间 参与了荷兰数学和计算机科学研究学会多个项目的工作 36 1989年的聖誕節期間 他決心開發一個新的腳本解釋程式 作為ABC語言的繼承者 并且用它替代Unix shell和C语言来进行系统管理 担负与Amoeba操作系统 英语 Amoeba operating system 之间的交互操作并进行异常处理 9 他是BBC電視劇 Monty Python的飛行馬戲團 的爱好者 所以选取了Python作为这个编程语言的名字 37 范羅蘇姆作为Python的主要開發者 独自担负这个项目的发展决策者职责 直到2018年7月12日 他宣布从終身仁慈獨裁者 BDFL 的职权上 永久休假 38 39 他在2019年1月至11月参与了第一届五人掌控委员会继续领导项目发展 40 41 在1991年2月 范羅蘇姆在alt sources上发布了最初代码 标记为版本0 9 0 42 这时就已经存在了带继承的类 异常处理 函数和核心数据类型list dict str等 在这个最初发行中就有了从Modula 3引进的模块系统 43 它的异常模型也类似于Modula 3 9 在1994年1月Python达到了版本1 0 这个发行版主要新特征是包括了由Amrit Prem提供的函数式编程工具 a href E5 8C BF E5 90 8D E5 87 BD E6 95 B0 html Python title 匿名函数 lambda a a href Map E9 AB 98 E9 98 B6 E5 87 BD E6 95 B0 html title Map 高阶函数 map a a href Filter E9 AB 98 E9 98 B6 E5 87 BD E6 95 B0 html title Filter 高阶函数 filter a 和 a href Fold E9 AB 98 E9 98 B6 E5 87 BD E6 95 B0 html title Fold 高阶函数 reduce a 44 Python 1 4增加了受Modula 3启发的关键字参数 英语 Named parameter 和对复数的内建支持 还包含了采取名字修饰的一种基本形式的数据隐藏 英语 Information hiding 45 Python 2 0於2000年10月16日發布 介入了列表推导式 这是从函数式编程语言SETL和Haskell中引入的 它还向垃圾回收系统增加了环检测算法 并且支持Unicode 46 Python 2 1支持了嵌套作用域 就像其他静态作用域语言一样 47 Python 2 2的重大革新是将Python的类型 用C写成 和类 用Python写成 统一入一个层级 使得Python的对象模型成为纯粹和一致的面向对象的模型 48 还增加了迭代器 49 受CLU和Icon启发的生成器 50 和描述器协议 51 Python 2 4加入了集合 英语 Set abstract data type 数据类型 和函数修饰器 52 Python 2 5加入了with语句 53 Python 3 0於2008年12月3日發布 它对语言做了较大修订而不能完全后向兼容 54 Python 3发行包括了2to3实用工具 它 至少部份的 自动将Python 2代码转换成Python 3代码 55 Python 3的很多新特性後來也被移植到舊的Python 2 6 2 7版本中 56 Python 2 7的产品寿命结束日期最初设定为2015年 出于对大量的现存代码不能前向移植到Python 3的关切 而将对它的支持延期至2020年 57 58 随着Python 2的产品寿命结束 2022年3月14日发布的macOS 12 3已经彻底移除了Python 2 59 当前只有Python 3的稳定版本3 10 3 11和预览版本3 12正在被完全支持 但仍提供对3 7 3 8和3 9版本的安全性修正 60 在2022年12月 活跃的Python核心开发者选举Pablo Galindo Salgado Gregory P Smith Emily Morehouse Brett Cannon和Thomas Wouters为2023年度 掌控委员会 的五位成员来领导这个项目 61 特徵與設計哲學 编辑Python是多范型编程语言 它完全支持结构化编程和面向对象编程 还有很多特征支持函数式编程和元编程比如元对象协议 元类和魔术方法 62 通过扩展还可以支持很多范型 包括面向切面编程 63 契约式设计 64 和逻辑编程 65 Python使用动态类型 在内存管理上采用引用计数和环检测相结合的垃圾回收器 66 它的特征还有动态名字解析 后期绑定 英语 late binding 即在程序执行期间绑定方法和变量的名字 Python對遵循LISP傳統的函数式编程提供了有限的支持 67 它提供了 a href Map E9 AB 98 E9 98 B6 E5 87 BD E6 95 B0 html title Map 高阶函数 map a a href Filter E9 AB 98 E9 98 B6 E5 87 BD E6 95 B0 html title Filter 高阶函数 filter a 和 a href Fold E9 AB 98 E9 98 B6 E5 87 BD E6 95 B0 html title Fold 高阶函数 reduce a 函数 列表推导式 字典 集合 英语 Set abstract data type 和生成器表达式 68 標準庫中的模組functools和itertools 实现了从Haskell和Standard ML借鉴来的函數式工具 69 Python的設計理念是 優雅 明確 簡單 它的一些重要準被合稱為 Python之禅 在Python解釋器内運行import this可以獲得完整的列表 下面举出其中首要 优美优于丑陋 明瞭优于隐晦 简单优于复杂 复杂优于凌乱 扁平优于嵌套 稀疏优于稠密 可读性很重要 Python開發者的方法论是 用一種方法 最好是只有一種方法來做一件事 显著不同于以Perl语言为代表的 不止一种方法去做一件事 風格 Python開發者在設計語言時 如果面臨多種選擇 一般會拒绝花俏的語法 而選擇明確没有或者很少有歧義的語法 范羅蘇姆认为ABC語言非常優美和强大 它没有取得成功的原因是不開放造成的 70 故而将Python本身設計為可擴充的 Python並不把所有的特性和功能都集成到語言核心 而是提供了豐富的API和工具 以便程式設計師能够輕鬆地使用Python C Cython來編寫擴充模組 Python还可以通过外界函数接口 英语 Foreign function interface 如标准库中的ctypes等 来访问动态链接库或共享库中C兼容数据类型并调用其中函数 71 以便于对用其他語言編寫的程式進行集成和封裝 Python開發人員盡量避開不成熟或者不重要的優化 一些針對非重要部位的加快運行速度的補丁 通常不會被合併到Python的官方实现CPython中 在某些對運行速度要求很高的情況 可以使用JIT技术的Python实现或扩展 72 語法 编辑主条目 Python語法及語義 Python的設計目標之一是讓程式碼具備高度的可閱讀性 它設計時盡量使用其它語言經常使用的標點符號和英文單字 讓程式碼看起来整潔美觀 Python语句之后的分号是可选的 作为动态语言不需要書寫 聲明 語句 不同於其他的靜態語言如C Pascal 縮排 编辑 Python語言利用縮排表示語句塊的開始和結束 越位規則 而非使用大括號或者某種關鍵字 增加縮排表示語句塊的開始 而減少縮排則表示語句塊的結束 根據PEP 8的規定 73 使用4個空格來表示每級縮排 a 使用Tab字符和其它數目的空格雖然都可以被解釋器識別 但不符合編碼規範 偏向使用Tab字符的程序員可以設置文本編輯器將Tab鍵轉換為4個空格 縮排成為了語法的一部分 並且Python開發者有意讓違反了 縮排規則 的程序不能通過解釋 关键字 编辑 Python有如下35个关键字或 保留字 它们不能用作标识符 74 75 and as assert async 注 1 await 注 1 break class continue def del elif else except False 注 2 finally for from global if import in is lambda None nonlocal 注 2 not or pass raise return True 注 2 try while with yield 注释 1 0 1 1 从Python 3 5开始 介入了async和await 76 2 0 2 1 2 2 从Python 3开始 介入了关键字True False和nonlocal 标识符 编辑 标识符就是名字 在ASCII范围内 U 0001 U 007F 可用于标识符的字符为 大写字母A至Z和小写字母a至z 下划线 以及数字0至9 但首字不可以用数字 有如下命名约定 77 spam 单下划线开头 弱 内部使用 标识 对于from M import 将不导入所有以下划线开头的对象 spam 单下划线结尾 为了避免与python关键字的命名冲突 spam 双下划线开头 在命名一个类特性的时候 采用名字修饰 比如在类SpamEggs内 spam将变成 SpamEggs spam 78 spam 双下划线开头双下划线结尾 指那些包含在用户控制的命名空间中的 魔术 方法或特性 比如 name doc init import file 等 建议永远不要将这样的命名方式应用于自己的变量或函数 在Python文献中经常使用的元语法变量 英语 metasyntactic variable 是spam和eggs 英语 Spam Monty Python 而非传统的foo和bar 78 語句和控制流 编辑 Python的语句包括 赋值语句 记号为等号 Python支持并行赋值 可以同时给多个变量赋值 还可以交换两个变量的值 b del语句 递归的进行删除 pass語句 充当NOP 表示此行為空 不執行任何操作 a href E6 96 B7 E8 A8 80 E7 A8 8B E5 BC 8F html title 斷言 程式 assert a 語句 用於程式調適階段時測試執行條件是否滿足 a href E6 A2 9D E4 BB B6 E9 81 8B E7 AE 97 E5 BC 8F html title 條件運算式 if a 語句 當條件成立時執行語句塊 經常與elif else配合使用 a href Foreach E5 BE AA E7 8E AF html title Foreach循环 for a 語句 遍历列表 字符串 字典 集合等迭代器 依次處理迭代器中的每個元素 a href While E8 BF B4 E5 9C 88 html title While迴圈 while a 語句 當條件為真時 循環執行語句塊 break语句 从循环中跳出 continue语句 越过这次迭代并继续进行下个项目 span class ilh all data orig title 异常处理语法 data lang code en data lang name 英语 data foreign title Exception handling syntax span class ilh page try span span class noprint ilh comment span class ilh lang 英语 span span class ilh colon span span class ilh link span lang en dir auto Exception handling syntax span span span span 語句 與except else finally配合使用 處理在程式執行中出现的異常情況 raise语句 抛出一个异常 class語句 用於定義類 它执行一块代码并将它的局部命名空间附属至一个类 def語句 用於定義函數和方法 return语句 用来从函数返回值 yield语句 使用它从一个生成器中返回一个值 c 在版本2 5之前 生成器是惰性迭代器 信息是单向的从生成器传递出来的 自从版本2 5 yield也是一个有返回值的运算符 能够将信息传递回到生成器函数中 79 自从版本3 3 信息可以传递通过多个堆栈层级 80 with語句 把一块代码包裹在一个上下文管理器之内 例如 在一块代码执行之前获取一个锁并且在此后释放这个锁 或打开一个文件并且在此后关闭它 它允许了资源获取即初始化 RAII 式行为并可替代常见的try finally惯用法 81 import语句 导入一个模块或包 有三种用法 import lt small 模块名字 small gt as lt small 别名 small gt from lt small 模块名字 small gt import from lt small 模块名字 small gt import lt small 定义1 small gt as lt small 别名1 small gt lt small 定义2 small gt as lt small 别名2 small gt 在Python中赋值语句所进行的操作是将一个名字绑定为到一个分立的 动态分配的对象的一个引用 因为名字的存储位置不 包含 这个指示的值 称它为 变量 是不准确的 这个名字可以随后在任何时候重新绑定到极大不同的各种类型的对象上 包括字符串 过程 具有数据和方法的复杂对象等等 因为名字是通用的引用持有者 给它关联一个固定的数据类型是不合理的 但是在给定时间一个名字总是被绑定到有一个类型的某个对象上 因此这是动态类型 接连的把一个共同的值赋值给多个名字 比如x 2 y 2 z 2 导致给3个名字和1个数对象分配存储 这3个名字都绑定到这1个数对象上 Python赋值语句的这种基础机制 不同于传统指令式编程语言比如C中的赋值 在这里右手侧的值被复制到给这个变量分配的存储位置之中 等号左手侧的变量名字是其符号地址 对为它声明的类型而言分配给它的内存是足够大的 Python支持并广泛使用异常处理作为检测错误状况和程序中其他 异常 事件的方式 Python风格提倡在可能出现错误状况的任何时候都使用异常 在Python中习惯上不在使用之前对访问一个文件或资源进行测试 而是先行尝试使用它 再捕获访问被拒绝引发的异常 d 经常为此援引的格言是葛麗絲 霍普贡献的EAFP 82 请求原谅比许可更容易 83 84 Python使用with语句处理资源 85 在进入一个作用域的时候调用一个函数而在离开它的时候调用另一个函数 这能防止忘记移除资源并且还可处理更复杂的状况比如异常 e Python官方实现不提供尾调用优化或头等续体 吉多 范罗苏姆曾声称永远都不会加以支持 86 目前只有第三方库支持 87 Python在版本2 5中通过扩展生成器 提供了对协程式功能的更好支持 79 f 版本3 4介入了综合性的异步I O框架标准化 在其中扩展了利用子生成器委托的协程 88 这个扩展自从Python 3 8被弃用 89 Python 3 5通过async await语法介入了对协程的显式支持 90 从版本3 7开始async await成为保留关键字 91 g 模块是定义可以被导入并重用于其他Python程序中的函数和类的Python正规 py文件 92 import语句找到一个模块 装载它 如果有需要的话初始化它 并且定义用来引用这个模块中代码的一个名字或一些名字 93 from import语句 找到 装载 必需时初始化一个模块 接着增加模块引用到局部命名空间 允许访问其中的函数和类而不采用模块引用 93 from import支持 选项来导入所有引用而非指名的特定函数或类 92 当模块被导入的时候 name 变量被设置成这个模块的名字 在Python解释器直接运行一个模块的时候 name 变量被设置为 main 这允许被设计用于导入的模块增加只在模块被直接运行时候执行的代码 92 94 dir 函数返回在当前局部作用域中或参数指定的对象中的名字的列表 95 表达式 编辑 Python中很多表达式与C和java类似 而另一些则与之不同 在Python中 算术运算的加法 减法 乘法 和取模 是与C和java相同的 但是除法的行为不同 在Python中有两种除法 它们是下取整除法 或整数除法 和浮点除法 96 Python增加了指数算符 Python有如下必须用于整数的位运算 amp 与 AND 或 OR 非 NOT 异或 XOR gt gt 右移 lt lt 左移 自从Python 3 5 97 介入了新的 中缀矩阵乘法算符 98 它已经用于了NumPy库 99 在Python中 有如下比较运算 大于 gt 小于 lt 等于 不等于 小于等于 lt 大于等于 gt 按值比较 对比于Java 它按值比较数 100 而按引用比较对象 101 在Java中比较对象的值可以采用equals 方法 Python的is is not算符可以用来比较对象的同一性 按引用比较 也就是比较两个变量是否引用了同一个对象 而in not in用于判断一个对象是否属于另外一个对象 在Python中 比较是可以链接起来的 比如a lt b lt c Python使用and or not表示逻辑运算与 或 非 不采用Java和C中所用的符号 amp amp 自从Python 3 8 介入了 赋值表达式 语法 它也叫做 命名表达式 或 海象 它将一个表达式赋值给一个标识符 同时还返回这个表达式的值 常用作更大的表达式的一部份 102 自从Python 3 9 介入了字典归并算符 和更新算符 103 Python支持列表推导式 h Python 2 4将列表推导式扩展至更一般性的生成器表达式 68 i Python 3 0和2 7又补全了字典推导式和集合推导式 j 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 104 列表是可变的 并且不能用作字典的键 Python中字典的键必须是不可变的 元组是不可变的 因而可以用作字典的键 假定这个元组的所有元素都是不可变的话 可以使用 算符来串接二个元组 这不会直接修改它们的内容 而是产生包含给定元组二者的元素的一个新元组 因此 给定变量t初始时等于 1 2 3 执行t t 4 5 时 首先求值t 4 5 它产生 1 2 3 4 5 接着赋值回到t 这在效果上 修改了 t的内容 尽管这还是遵守了元组对象的不可变本性 Python有 序列解包 特征 多个表达式 其中每个都可求值成能被赋值的东西 变量 可写的属性等 以与形成元组文字 literal 相同的方式 关联起来作为一个整体 放置在赋值语句等号的左手侧 这个语句预期在等号的右手侧有一个 可迭代 对象 在迭代它的时候产生同左手侧给出的可写表达式相同数目的值 这个语句对它进行迭代并把每个产生的值赋值给左手侧对应的表达式 105 这个特征允许从一个单一函数返回多个值 自从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 字符串 106 blah blah eggs 2 f spam blah eggs eggs m Python拥有各种字符串文字 英语 string literal 由单引号 或双引号 界定的字符串 不同于Unix shell Perl和受Perl影响的语言 单引号和双引号功能相同 这二种字符串都使用反斜杠 作为转义字符 在Python 3 6中字符串插值 英语 String interpolation 可作为 格式化字符串 而获得到 106 三引号字符串 开始和结束于三个单引号或双引号的序列 它们可以跨越多行 其功能就像shell Perl和Ruby中的here文档 n 原始字符串 英语 String literal Raw strings 变体 用给字符串文字前导一个r来指示 转义序列不被解释 因此在文字反斜杠常见的地方很有用 比如正则表达式和Windows风格的路径 o 可比较于C 中的 引用 Python允许连续出现和只用空白分隔 包括换行 的字符串文字 可能使用了不同的引用约定 它们被聚合成一个单一的更长的字符串 107 p Python拥有在列表上的数组索引和数组分片 英语 array slicing 表达式 表示为a key a start stop 或a start stop step 索引是基于零的 负数是相对于结尾的 分片从 开始 start 索引直到但不包括 停止 stop 索引 分片的第三个参数叫做 步长 step 或 间隔 stride 允许元素被跳过和用负数指示反向 分片索引可以省略 例如a 这返回整个列表的一个复本 q 分片的每个元素都是浅层复制 英语 Object copying 的 在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声明 用于赋值到给非局部变量 英语 Non local variable u Python可以指定形式参数的缺省值 在函数定义时于形式参数序列中以param value样式进行一次性初始化 形式参数在初始化之后保持既有绑定 函数的后续调用可继续对它进行访问或变更 v 在函数调用时为有缺省值的形式参数提供实际参数是可选的 Python支持位置实际参数和关键字实际参数 函数调用时 实际参数可以如同C语言那样按照位置与形式参数匹配 也可以采用命名参数 英语 Named parameter 或称为关键字实际参数 即kwarg value样式的实际参数 使用不对应实际参数的特殊形式参数 和 可以将参数序列分为唯位置参数 108 可位置可关键字参数和唯关键字参数三部份 有缺省值的形式参数之后不能跟随无缺省值的可位置形式参数 w 在一个函数调用的实际参数序列中 关键字实际参数必须出现在位置实际参数之后 在位置和关键字形式参数序列末尾可以分别有 args或 kwargs这样的形式参数 它们对应于在函数调用时提供的 超出形式参数序列规定而无所对应的多个实际参数 在形式参数名字前加一个 号 该形式参数args是tuple类型 对应可变数目的位置实际参数 在形式参数名字前加 号 该形式参数kwargs是dict类型 对应可变数目的关键字实际参数 x 在位置实际参数已经在一个序列类型如列表或元组的对象中的情况下 在引用它的变量前加一个 号传递给函数 则其中所有元素解包为多个位置实际参数 关键字实际参数在字典中则加 号来传递给函数 修饰器 decorator 是用来修改一个函数 方法或类定义的任何可调用Python对象 将正被定义的最初对象传递给修饰器 它返回一个修改后的对象 接着把它绑定到在定义中那个名字 Python修饰器部份受到Java注解的影响 而有类似的语法 修饰器语法是纯粹的语法糖 使用 作为关键字形成修饰符 修饰器是一种形式的元编程 它们增强它们所修饰的函数或方法的行动 y 多个修饰器可以链接起来 通过在毗连的行上放置多个修饰符 或者使用中间变量 z 函数修饰器的正规用法包括 用来建立类方法或静态方法 51 实现多方法 增加函数特性 跟踪 英语 Tracing software 设置先决条件和后置条件 同步 109 此外更远大的用法包括 尾调用消除 110 记忆化甚至改进修饰器的写作 111 为了增强代码的可读性 可以在函数后书写 文档字符串 简称docstrings 用于解释函数的作用 参数的类型与意义 返回值类型与取值范围等 可以使用内置函数help 打印出函数的使用帮助 aa 自从Python 3 5 开始支持类型提示 112 可以标注函数的参数与返回值 113 此特性可方便IDE对源代码进行更深入的分析 ab 对象及其方法 编辑 Python支持大多数面向对象编程技术 在Python中所有东西都是对象 包括类 函数 数和模块 它允许多态性 不只是在类层级 英语 Class hierarchy 之内而且通过采用鸭子类型的方式 任何对象可以用于任何类型 只要它有适当的方法和特性 attribute 就能工作 Python天然支持类的继承包括多重继承 为此采用C3线性化或方法解析次序 MRO 算法 还支持mixin Python支持元类 114 它是增进类的功能的高级工具 Python使用名字修饰有限的支持私有变量 对象的特性可以被提取为一个字典 115 在Python中不强制使用访问子与变异子方法来访问数据成员的面向对象编程信条 就像Python提供函数式编程构造但不尝试要求参照透明性 英语 referential transparency 无副作用 一样 它提供对象系统但不要求面向对象编程行为 对象的方法是附属于这个对象的类的函数 对于正常的方法和函数 语法instance method arguments 是Class method instance arguments 的语法糖 Python的方法有显式的 span class ilh all data orig title this 计算机编程 data lang code en data lang name 英语 data foreign title this computer programming span class ilh page self span span class noprint ilh comment span class ilh lang 英语 span span class ilh colon span span class ilh link span lang en dir auto this computer programming span span span span 形式参数用来访问实例数据 对比于在其他一些面向对象编程语言 比如C Java Objective C或Ruby 中隐式的self或 span class ilh all data orig title this 计算机编程 data lang code en data lang name 英语 data foreign title this computer programming span class ilh page this span span class noprint ilh comment span class ilh lang 英语 span span class ilh colon span span class ilh link span lang en dir auto this computer programming span span span span 关键字 116 在Python中 self可以被看作是一个习惯用法 它可以被换为任何其它合法的参数名 ac Python支持一些以 开始和结束的特殊方法名 它们用于实现运算符重载和实现多种特殊功能 62 在Python中 可以通过定义特殊方法来重载运算符 比如在一个类上定义 add 将允许在这个类的实例上使用 算符 在Python中 当一个子类的方法覆盖了超类方法的时候 通过调用super method来调用与子类的self method方法同名超类方法 117 ad Python允许通过使用 classmethod和 staticmethod修饰符来分别建立类方法和静态方法 给类方法的第一个实际参数是类对象而非对实例的self引用 静态方法没有特定的第一个实际参数 实例或类对象都不固定的传递给静态方法 ae 在Python中定义了一个或多个特殊方法 get set delete 的类可以用作描述器 descriptor 118 如此建立一个描述器的实例作为另一个类的一个类成员 使得这个实例成为此另一个类的属性 property 使用与特性 attribute 访问相同的语法 访问一个实例对象中的这个成员属性 af Python的property内建函数 将一个类中特殊定义的访问一个特性的那些方法包装成的这个类的一个属性 119 ag 类型 编辑 Python 3中的标准类型层次结构 Python使用鸭子类型并拥有有类型的对象和无类型的变量名字 在编译期不检查类型约束 而宁愿在一个对象上的操作出现可能的失败 表现出这个给定对象不具有适合的类型 尽管是动态类型系统 Python却是强类型的 禁止没有明确定义的操作 比如加一个数到一个字符串 而不是默默的去尝试转换使其有意义 Python支持广泛的类型和类的内省 类型是type的实例 可以被读取和比较 Python有着范围广泛的基本数据类型 同时具备常规的整数和浮点算术 它透明的支持任意精度算术 复数和十进制浮点数 英语 Decimal floating point Python支持种类繁多的字符串操作 在Python中字符串是不可变的 所以在其他编程语言中可能就地改变字符串的字符串操作比如字符替换 在Python中返回新的字符串 Python的一个非常有用方面就是搜集 或称容器 类型的概念 一般的说 搜集是以一种易于引用或索引的方式包含其他对象的对象 Python对建立容器类型的对象有着语法上的支持 ah 搜集有二种基本形式 序列和映射 有次序的序列类型是列表 动态数组 英语 array data type 元组和字符串 所有序列类型都是位置索引的 从0到长度 1 并且除了字符串 都可以包含任意类型的对象 在同一个序列中包括多种类型的对象 字符串和元组是不可变的 使得它们成为字典的键的完美候选者 在另一方面 列表是可变的 元素可以被插入 删除 修改 添加或就地排序 在另一方面 映射是以 字典 形式实现的无次序的类型 它将一组不可变的键映射到相应的元素上 非常像数学函数 在字典中的键必须是不可变的Python类型 比如整数或字符串 因为在底层它们是通过散列函数实现的 字典还是语言内部的中心 因为它们居于所有Python对象和类的核心 在变量名字 字符串 和这个名字所引用的值之间的映射就存储为字典 而这些字典可以通过对象的 dict 特性直接访问 集合 英语 Set abstract data type 搜集类型是在版本2 4中增加入语言核心的 集合是不包含重复项的无索引 无次序的搜集 并且实现了集合论运算比如并集 交集 相对补集 对称差和子集测试 有二种类型的集合 可变的set和不可变的frozenset 集合中元素必须是可散列的 比如说 frozenset可以是正规set的元素而反之不行 Python还提供了广泛的搜集操纵能力比如内建的包含元素检查和通用迭代协议 Python允许编程者使用类定义自己的类型 48 类在面向对象编程中是最经常使用的 类的新实例是通过调用这个类的构造器而创建的 而类都是元类type的实例 type是type元类自身的实例 ai 这允许了元编程和反射 在版本3 0之前 Python有两种类 旧式的和新式的 120 二种样式的语法是一样的 不同在于是否直接或间接的继承自类object 所有新式类都从object继承并且是type的实例 在Python 2系列2 2以上 二种类都可以使用 48 在Python 3 0中淘汰了旧式类 长期规划是支持渐进类型 英语 gradual typing 121 并且自从Python 3 5 语言的语法允许指定静态类型 但在缺省实现CPython中不检查它们 有实验的叫做 mypy 的可选的静态类型检查器支持编译期类型检查 122 Python 3内置类型总结 类型 可变性 描述 语法例子bool 不可变 布尔值 span class kc True span span class kc False span int 不可变 理论上无限制大小的整数 123 span class mi 42 span float 不可变 双精度浮点数 精度是机器依赖的但实际上一般实现为64位IEEE 754数而带有53位的精度 124 span class mf 1 414 span complex 不可变 複數 具有实部和虚部 span class mi 3 span span class o span span class mf 2 7 span span class n j span range 不可变 通常用在循环中的数的序列 规定在for循环中的次数 125 span class nb range span span class p span span class mi 1 span span class p span span class mi 10 span span class p span span class nb range span span class p span span class mi 10 span span class p span span class o span span class mi 5 span span class p span span class o span span class mi 2 span span class p span str 不可变 字符串 Unicode代码点序列 span class s1 Wikipedia span span class s2 Wikipedia span Spanning multiple lines bytes 不可变 字节序列 span class sa b span span class s1 Some ASCII span span class sa b span span class s2 Some ASCII span span class nb bytes span span class p span span class mi 119 span span class p span span class mi 105 span span class p span span class mi 107 span span class p span span class mi 105 span span class p span bytearray 可变 字节序列 span class nb bytearray span span class p span span class sa b span span class s1 Some ASCII span span class p span span class nb bytearray span span class p span span class sa b span span class s2 Some ASCII span span class p span span class nb bytearray span span class p span span class mi 119 span span class p span span class mi 105 span span class p span span class mi 107 span span class p span span class mi 105 span span class p span list 可变 列表 可以包含混合的类型 span class p span span class mf 4 0 span span class p span span class s1 string span span class p span span class kc True span span class p span span class p span tuple 不可变 元组 可以包含混合的类型 span class p span span class mf 4 0 span span class p span span class s1 string span span class p span span class kc True span span class p span span class p span span class s1 single element span span class p span span class p span dict 可变 键 值对的关联数组 或称字典 可以包含混合的类型 键和值 键必须是可散列的类型 span class p span span class s1 key1 span span class p span span class mf 1 0 span span class p span span class mi 3 span span class p span span class kc False span span class p span span class p span set 可变 无序集合 英语 Set abstract data type 不包含重复项 可以包含混合的类型 如果可散列的话 span class p span span class mf 4 0 span span class p span span class s1 string span span class p span span class kc True span span class p span span class nb set span span class p span frozenset 不可变 无序集合 英语 Set abstract data type 不包含重复项 可以包含混合的类型 如果可散列的话 span class nb frozenset span span class p span span class mf 4 0 span span class p span span class s1 string span span class p span span class kc True span span class p span types EllipsisType 不可变 省略号 英语 Ellipsis programming operator 占位符 用作NumPy数组的索引 span class o span span class bp Ellipsis span types NoneType 不可变 表示值缺席的对象 在其他语言中经常叫做null span class kc None span types NotImplementedType 不可变 可从重载运算符返回的占位符 用来指示未支持的运算数 operand 类型 span class bp NotImplemented span 除了各种数据类型 Python解释器内建了还有很多其他类型 比如上下文管理器类型 模块 方法 代码对象 类型对象 内部对象等类型 数学 编辑 Python的算术运算使用平常的符号 下取整除法算符 和模除 这里的余数可以是负数 比如4 3 2 它还有指数算符 比如5 3 125及9 0 5 3 0 和矩阵乘法算符 98 这些算符就像在传统数学中一样运算 具有同样的优先级规则 中缀算符 还可以分别表示取原数和取相反数的一元算符 在整数之间的除法 产生浮点数结果 除法 的表现随着版本不同而有着显著变化 126 Python提供了round 函数用于把一个浮点数修约成最近的整数 127 Python允许由比较运算链接起来的布尔表达式表现得如在数学中常用的一样 比如 表达式a lt b lt c测试a小于b并且b小于c 128 C派生语言不一样的解释这个表达式 在C中 这个表达式将首先求值a lt b 结果为0或1 接着把这个结果比较于c 129 Python对所有整数运算使用任意精度算术 在decimal模块中的Decimal类型 类提供十进制浮点数到预定义的任意精度并有多种修约模式 130 在fractions模块中的Fraction类提供任意精度的有理数 131 由于Python有着广泛的数学库 除了求绝对值函数abs 列入内建函数之外 大多数数学函数处于math和cmath模块内 前者用于实数运算 而后者用于复数运算 aj 特别是 第三方库NumPy进一步扩展了固有能力 Python经常被用作科学脚本语言来处理如数值数据处理和操纵等问题 132 133 标准库 编辑Python拥有一个强大的标准库 134 Python语言的核心只包含数值 字符串 列表 字典 文件等常见类型和函数 而由Python标准库提供了系统管理 网络通信 文本处理 数据库接口 图形系统 XML处理等额外的功能 Python标准库的主要功能有 文本处理 英语 Text processing 包含文本格式化 正则表达式 文本差异计算与合并 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直譯器進入互動式命令列的環境 你可以在提示符號 gt gt gt 旁輸入print Hello world 按Enter鍵輸出結果 gt gt gt print Hello world Hello world 计算正数的阶乘的程序代码 n int input 键入一个数 就会打印它的阶乘 if n lt 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直譯器 135 Python属于动态语言 将Python程序编译成中间形式的字节码 136 并接着在它的虚拟机上执行 137 相较于C C 等编译成机器码的编译语言而言运行速度较慢 138 主要实现CPython 官方的直譯器 需要区别于其他直譯器的时候才以CPython称呼 MicroPython和CircuitPython 英语 CircuitPython 它们是为微控制器而优化的Python 3变体 Pyston CPython 3 8 12的分叉 具有包括JIT的额外性能优化 139 还将其JIT部份作为扩展模块pyston lite autoload来单独发行 140 Cinder 由Meta开源发布 它是Meta内部使用的面向性能的CPython 3 10分叉 具有包括JIT的很多优化 141 PyPy 用RPython书写的Python实现 其主线版本兼容至CPython 3 8 测试版本兼容至CPython 3 9 它采用了跟踪JIT 英语 Tracing just in time compilation 缺省支持stackless模态 Stackless Python 实现微线程 英语 microthread 的CPython 3 8分叉 它不使用C内存堆栈 因而允许大规模并发程序 到其他语言的交叉编译器Cython 将扩充了静态类型的Python超集编译成C或C Numba 使用LLVM 将包括很多NumPy函数的聚焦数值计算的Python子集 翻译成快速的机器码 它为在CPU和GPU上并行化Python代码提供了大量选项 Pyjion CPython的JIT扩展 它将Python代码编译成本机CIL 从而使用 NET CLR来执行它 142 Nuitka 英语 Nuitka 用Python书写的到C11或C 03的优化编译器 英语 Optimizing compiler 它能建立不需单独的安装器就能运行的可执行程序 143 Pythran 将聚焦于科学计算的Python子集编译成C 11的提前编译器 英语 Ahead of time compilation 它能利用上多核和SIMD指令单元 144 MyHDL 英语 MyHDL 将Python编译成VHDL 仍在维护中的旧版本实现有 IronPython 它是面向 NET和Ecma CLI的Python 2 7实现 它还有处在开发状态的3 4版本实现 Jython 它是用Java实现的Python 2 7 开发环境 编辑通用文本编辑器 编辑 很多并非集成开发环境软件的文本编辑器 也对Python有不同程度的支持 并且加上专门为Python设计的编辑器插件也会有很高的可用性 Visual Studio Code Atom Eclipse IntelliJ IDEA emacs NetBeans SlickEdit TextMate Vim Sublime Text EditPlus UltraEdit PSPad Notepad 专用开发环境 编辑 适用于Python的集成开发环境 IDE 软件 除了标准二进制发布包所附的IDLE之外 还有许多其他选择 其中有些软件设计有语法着色 语法检查 运行调试 自动补全 智能感知等便利功能 由于Python的跨平台出身 这些软件往往也具备各种操作系统的版本或一定的移植性 IDLE Python 标准 IDE 一般随Python而安装 支持较少的编辑功能 调试功能也比较弱 Eric 基于PyQt的自由的IDE 支持自动补全 智能感知 自动语法检查 工程管理 svn mercurial集成 自动单元测试等功能 具有可扩展的插件系统 通过可选插件支持Git集成 调试功能与Visual Studio和Eclipse类似 Spyder 开源的跨平台科学计算IDE PyScripter 英语 PyScripter 功能较全的开源IDE 使用Delphi开发 PyCharm 由JetBrains公司出品 具备一般IDE的功能 比如调试 语法高亮 Project管理 代码跳转 智能提示 自动完成 单元测试 版本控制等等 另外 它还提供了一些功能用于Django开发 同时支持Google App Engine 还支持IronPython 它是商业软件 但也具有社区版和教育版 Komodo 英语 Komodo IDE 和Komodo Edit 英语 Komodo Edit 后者是前者的免费精简版 WingIDE 英语 WingIDE 商业软件 有免費的功能有限的Wing IDE 101 適用於入門者教學 應用 编辑 Python Powered 主条目 Python软件列表 英语 List of Python software 在很多作業系統裡 Python是標準的系统元件 大多數Linux發行版和macOS都集成了Python 可以在終端機下直接執行Python 雖然Python可被粗略地分類為腳本語言 Python的支持者較喜歡稱它為一種高階動態語言 常像 胶水 一样被用来连接软件组件 已经显著的区别于Unix shell Windows PowerShell这样的语言 基于Python的xonsh 是跨平台的 青睐Unix的shell语言和命令行界面 145 Python社群提供了大量的功能覆盖众多领域的第三方模組 其使用方式与标准库类似 第三方模块可以使用Python Cython或者C编写 软件工具SWIG和SIP 英语 SIP software 通过定义接口文件或规定文件的方式 可以将C C 编写的程序库包装为Python模块 Python解释器本身也可以被集成到其它需要腳本語言的程式内 pip是事实标准和官网推荐的用Python书写的软件包管理系统 146 它通常连接到叫做Python包索引的一个公开软件包在线仓库 pipenv自动为用户项目建立和管理虚拟环境 还在安装 卸装软件包的时候 向Pipfile文件增加 移除这个软件包 147 pyenv可以安装并轻易切换多个版本的Python 148 自从2003年 Python始终排行于TIOBE编程社区索引 英语 TIOBE Programming Community Index 前十最流行编程语言 在2021年10月它首次达到了第一名最流行语言 居于C和Java之前 149 并被选为2007年 2010年 2018年 2020年和2021年的年度编程语言 149 網絡服务 编辑 参见 Web服务 Python定義了WSGI標準應用接口来協調Http伺服器與基於Python的Web程式之間的溝通 比如 通過mod wsgi 英语 mod wsgi 模組 Apache可以運行用Python編寫的Web程式 Zope是著名的用Python编写的开源的Web应用服务器 Tornado是用Python语言写成的非阻塞式web服务器 也是轻量级的Web框架 Python對於各种網路協定的支援很完善 因此經常被用於編寫伺服器軟體 網路爬蟲等Web開發 用Python编写的一些Web框架 可以讓程式設計師輕鬆地開發和管理複雜的Web程式 著名的第三方Web框架和函数库 Django MTV架构 150 的Web开发框架 注重组件的重用性和 可插拔性 快速开发和DRY法则 web2py MVC架构的全栈Web框架 聚焦于快速开发 偏好约定优于配置方式 TurboGears MVC架构的混合Web框架 可以担任全栈框架或微框架二者 Pyramid 极简主义的Web框架 不预定持久化方式 它是Pylons计划的一部分 Flask 微Web框架 不要求特定的工具或库 aiohttp 轻量级的Web框架 151 采用的是Python3的asyncio异步特性 Twisted 事件驱动的网络编程框架 它支援多數標準的網路協定 包含客户端和伺服器 並且提供了多種工具 被廣泛用於編寫高性能的伺服器軟體 Requests 适合于常人使用的HTTP库 封装了许多繁琐的HTTP功能 极大地简化了HTTP请求所需要的代码量 Beautiful Soup 用来解析HTML XML的一个简单易用Python包 gevent 是基于协程的高性能并发网络编程库 152 使用greenlet在libev或libuv之上提供了高层的同步式API 图形用户界面 编辑 参见 GUI 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 英语 GIO software 和GStreamer等库使用的对象系统 Kivy 用于开发多点触控应用软件的开源Python库 采用了自然用户界面 NUI WxPython GUI编程框架wxWidgets的Python包装库 它与MFC的架构相似 PySimpleGUI 将Tkinter Qt WxPython和Remi 153 的GUI框架变换成简单的接口 154 Gooey 将几乎所有Python 3控制台程序用一行代码转变成GUI应用 155 Pyforms 开发能够在三种不同环境即桌面GUI 终端和网页下执行的程序的Python框架 156 数据科学 编辑 重要的数据科学用第三方软件库有 NumPy Python的基础性的科学计算软件库 提供了矩阵 线性代数 傅立叶变换等的解决方案 SciPy 用Python实现了MATLAB所有功能的软件库 使用NumPy的多维阵列作为基本数据结构 CuPy 英语 CuPy NumPy SciPy兼容的GPU加速的阵列库 157 它可在NVIDIA CUDA或AMD ROCm 英语 ROCm 平台上充当其即插即用替代者 来运行现存的NumPy SciPy代码 pandas 用于数据分析和数据操纵的软件库 建造在NumPy基础上 提供了类似于R语言中同名对象的加标签数据结构 数据帧 158 和统计函数等 Dask 英语 Dask software 伸缩范围从笔记本电脑至计算机集群的并行计算库 159 它由两部份构成 为计算而优化的动态任务调度 和 大数据 搜集如并行的阵列 数据帧和列表 这些搜集将常用接口如NumPy pandas或Python迭代器 扩展到大过内存或分布式的环境 并行的搜集运行在动态任务调度器顶上 matplotlib 用于Python和NumPy的绘图 英语 Plotter 库 实现类似MATLAB的绘图功能 scikit learn 基于NumPy SciPy Joblib 160 和threadpoolctl 161 的機器學習软件库 實現許多知名的機器學習演算法 其绘图功能依赖于matplotlib Dash 基于React Flask和Plotly 英语 Plotly 公司的Plotly js 162 之上的框架 它将现代用户界面元素如下拉选单 滑动条 英语 Slider computing 和图形 直接连结至分析型Python代码 163 它和Streamlit 164 Panel 165 和Voila 166 是被称为 仪表板 的数据可视化工具 167 PyMC 基于Theano的概率编程库 用于贝叶斯统计建模和概率机器学习 TensorFlow Google开发的一个端到端开源机器学习平台 它提供了Python API 168 其中实现了Keras API 169 Keras现在是在TensorFlow 2上建立的深度学习高层API SciKeras是对Keras模块的scikit learn兼容的包装器 170 PyTorch Meta在Torch 英语 Torch machine learning 基础上开发的开源的Python软件包 提供了具有强大的GPU加速的张量计算 和建立在基于tape的自动梯度系统上的深度神经网络 skorch是包装了PyTorch的scikit learn兼容的神经网络库 171 JAX 英语 Google JAX Google开发的拥有可组合的函数变换的开源机器学习框架 172 结合了修改版本的针对NumPy的自动梯度库Autograd 173 和TensorFlow中的加速线性代数库XLA 174 它使用XLA来在GPU和TPU上编译和运行NumPy程序 JAX除了用于开发新的人工神经网络软件库比如Flax 175 还用于概率编程库比如NumPyro 176 和物理引擎比如Brax 177 Ray 对人工智能及Python应用的运行规模进行伸缩的统一框架 178 它构成自一个核心的分布式运行时间系统 和加速机器学习工作负载的软件库工具箱 Ray AIR 它支持TensorFlow或PyTorch 可集成于Dask 英语 Dask software Apache Spark和Mars 179 可以部署在Kubernetes集群和云端VM之上 其它种类的库 编辑 SymPy 支持数学符号运算如微积分等的软件库 用于提供计算机代数系统 SQLAlchemy 针对关系型数据库的对象关系映射 ORM 工具 Pillow 英语 Python Imaging Library 是基于Python的图像处理库 180 它支持广泛的图形文件格式 分叉于已终止的PIL PyOpenGL 到OpenGL 1 1 4 4和有关API的最常用跨平台Python绑定 181 ModernGL 在OpenGL 3 3 核心上的Python包装器 182 它简化了简单图形应用如科学模拟 游戏和用户界面的创建 VisPy 高性能交互式2D 3D数据可视化库 183 它通过OpenGL库利用现代GPU的计算能力来显示非常大的数据集 PyCUDA和PyOpenCL 不同于Nvidia尽可能匹配C API的cuda python 184 PyCUDA提供对CUDA并行计算API的Python风格访问 185 PyOpenCL提供对OpenCL并行计算API的Python风格访问 186 Kornia 基于PyTorch的可微分计算机视觉库 187 pygame 开发视频游戏的Python软件库 基于了SDL库 188 pyglet Python编写的面向对象的游戏和多媒体库 利用了FFmpeg库 pythonnet 针对 NET的程序包 189 它可以近乎无缝的集成 NET通用语言运行库 CLR Fabric 经由SSH远程执行shell命令的高层库 190 它产生有用的Python对象作为回馈 Prefect 现代工作流程编排框架 191 它易于建造 调度和监控健壮的数据流水线 PyInstaller 将Python应用和它的依赖项捆绑成一个单一的包 192 从而不需要安装Python解释器或任何模块就可以运行应用 应用软件 编辑 有一些Linux發行版的安裝器使用Python語言編寫 在RPM系列Linux发行版中 有一些系统组件就是用Python编写的 一些著名的互联网公司在内部使用Python 141 一些遊戲比如EVE 使用Python編寫遊戲的邏輯 伺服器 如下著名应用使用Python编写或将它作为嵌入式脚本 IPython 以多种编程语言进行交互式计算的命令shell和Jupyter的内核 最初为Python开发 它提供了内省 富媒体 shell语法 tab补全 英语 Command line completion 和历史 Conda 跨平台的 语言无关的二进制包管理器 它被Anaconda发行采用 SCons 软件建造工具 它可代替make构建编译程序 Ubiquity Ubuntu的安裝器 Anaconda Red Hat Enterprise Linux和Fedora的安裝器 Portage Gentoo Linux使用Python編寫的軟件包管理系统 Gunicorn 英语 Gunicorn 使用Python语言编写的WSGI Web服务器 Plone 基于Zope的内容管理系统 Mezzanine 英语 Mezzanine CMS 基于Django框架的内容管理系统 Odoo ERP软件 有开源社区版 SageMath 覆盖许多数学功能的应用软件 Veusz 英语 Veusz 用Python PyQt和NumPy写成的科学绘图软件 可生成能够出版的PDF或SVG输出 LibreOffice 自从2013年的版本4 0开始 包含了Python并意图用它来替代Java 它的Python脚本提供器是核心特征 193 Blender 開源3D繪圖軟體 使用Python作為建模工具與GUI語言 Inkscape 开源的SVG矢量图形编辑器 使用Python用于插件 Panda3D 英语 Panda3D 开源游戏引擎 包括了图形 音频 I O 碰撞侦测和其他与3D游戏有关的功能 使用Python作为游戏开发语言 194 社群流行 编辑 PyCon 各地社群舉辦的會議 通常每年舉辦 各社群在會議中討論Python相關的議題 Python Discord 参与者众多的Python社区 195 PyLadies 英语 PyLadies 由女性社群發起的社群 主要注重於發展Python的女性程式設計社群 Django Girls 英语 Django Girls 使用Django網頁設計框架 推廣使用Python進行網頁設計的技術 影響的语言 编辑Python的设计和哲学已经影响了很多其他编程语言 Boo 使用了缩进 类似的语法和类似的对象模型 196 Cobra 英语 Cobra programming language 使用了缩进和类似的语言 而且它的致谢文档将Python列为影响它的首要语言 197 CoffeeScript 是交叉编译至JavaScript的编程语言 有受Python启发的语法 ECMAScript JavaScript 从Python借鉴了迭代器和生成器 198 GDScript 是非常类似Python的脚本语言 内置入了Godot游戏引擎 199 Genie 基于Vala编译器的具有近似Python语法的一种语言 Go 设计为 有动态语言如Python的工作速度 200 并共享了相同的分片数组的语法 Groovy 受到Python等动态类型语言的影响 201 Nim 使用缩进和类似的语法 202 Swift 是Apple开发的编程语言 有受Python启发的语法 203 Ruby的创建者松本行弘曾说过 我想要一种脚本语言 比Perl更加强力而且比Python更加面向对象 因此我决定设计自己的语言 204 Julia设计原则中有一条是 像Python一样可用于通用编程 25 代码示例 编辑 縮排示例 def print something age if age lt 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 lt 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 lt stop at lt n return 引发StopIteration异常 composite False for p in primes if not n p composite True break elif p 2 gt n break if not composite primes append n yield n 上述函数的隐式迭代用例 for i in generate primes 迭代于100以内所有素数上 if i gt 100 break print i 在生成器表达式中使用上述函数 定义了一个惰性的 巨大而并非无限的搜集的示例 from itertools import islice primes under million i for i in generate primes if i lt 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 gt format item yield item except GeneratorExit return def consume item None try while True item yield item print consuming item lt 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 gt 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 lt 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 列表的推导式示例 比如 gt gt gt 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 lt pivot pivot qsort x for x in L 1 if x gt pivot 生成器表达式示例 比如 gt gt gt sum x x for x in range 10 285 gt gt gt dict n n n for n in range 5 0 0 1 1 2 4 3 9 4 16 gt gt gt 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 gt gt gt 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 gt gt gt x 3 for x in range 4 3 4 5 6 匿名函数示例 gt gt gt from functools import reduce gt gt gt reduce lambda x y x y 1 2 3 4 5 15 gt gt gt fac lambda n 1 if n lt 2 else n fac n 1 gt gt gt fac 5 120 gt gt gt map fac 1 2 3 4 5 1 2 6 24 120 不动点组合子示例 gt gt gt Y lambda f lambda x x x lambda y f lambda args y y args gt gt gt fac lambda f lambda n 1 if n lt 2 else n f n 1 gt gt gt Y fac 5 120 gt gt gt fib lambda f lambda n 0 if n 0 else 1 if n 1 else f n 1 f n 2 gt gt gt Y fib 6 8 gt gt gt map lambda f lambda x x x lambda y f lambda args y y args lambda f lambda n 1 if n lt 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 序列解包 可迭代解包和字典解包示例 gt gt gt a 1 2 3 b 4 5 gt gt gt i j k a gt gt gt print i j k 1 2 3 gt gt gt c a b gt gt gt c 1 2 3 4 5 gt gt gt d a b gt gt gt d 1 2 3 4 5 gt gt gt e a b gt gt gt e 1 2 3 4 5 gt gt gt f as 1 bs 2 g cs 3 ds 4 gt gt gt h f g gt gt gt 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 多行字符串文字带有字符串插值 英语 String interpolation 使用了format方法 的示例 print 亲爱的 recipient 我希望你离开Sunnydale并永不返回 不是很爱你的 sender format sender 吸血鬼猎人Buffy recipient Spike 原始字符串的示例 gt gt gt Windows路径 即使是原始字符串也不能结束于反斜杠 gt gt gt r C Spam Eggs Ham File lt stdin gt line 1 r C Spam Eggs Ham SyntaxError EOL while scanning string literal gt gt gt dos path r C Spam Eggs Ham 通过增加尾随的空格 gt gt gt dos path rstrip 并接着移除它来避免错误 C Spam Eggs Ham gt gt gt quoted dos path r format dos path gt gt gt quoted dos path C Spam Eggs Ham gt gt gt 匹配具有可能的反斜杠引用的引用字符串的正则表达式 gt gt gt import re gt gt gt re match r quoted dos path group 1 rstrip C Spam Eggs Ham gt gt gt code spam 2 eggs gt gt gt 反转有二个参数的函数调用的两个实际参数 gt gt gt re sub r s r 2 1 code spam eggs 2 gt gt gt 注意如果实际参数中有圆括号或逗号则上例无效 字符串文字串接示例 gt gt gt title SICP in Python CS61A Online Textbook 等价于 gt gt gt title SICP in Python CS61A Online Textbook 下面几个判断语句为真 表示列表分片结果符合预期 gt gt gt nums 1 3 5 7 8 13 20 gt gt gt nums 2 5 5 7 8 从下标为2的元素切割到下标为5的元素 但不包含下标为5的元素 True gt gt gt nums 1 3 5 7 8 13 20 切割到最后一个元素 True gt gt gt nums 3 1 3 5 7 从最开始的元素一直切割到倒数第3个元素 True gt gt gt nums 1 3 5 7 8 13 20 返回所有元素 改变新的列表不会影响到nums True gt gt gt 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 是个闭包 函数的形实参数二者结合示例 例如 gt gt gt def spam a a append LovelySpam gt gt gt def eggs b b 100 实际上是重新绑定了另一个整型对象100 gt gt gt a gt gt gt b 10 gt gt gt spam a gt gt gt eggs b gt gt gt print a LovelySpam gt gt gt print b 10 局部变量和全局变量示例 gt gt gt def spam print b gt gt gt b 10 gt gt gt spam 10 gt gt gt def spam print b b 100 gt gt gt b 10 gt gt gt spam Traceback most recent call last File lt stdin gt line 1 in lt module gt File lt stdin gt line 2 in spam UnboundLocalError local variable b referenced before assignment gt gt gt def spam print b global b b 100 File lt stdin gt line 3 SyntaxError name b is used prior to global declaration gt gt gt def spam global b print b b 100 gt gt gt b 10 gt gt gt spam 10 gt gt gt b 100 非局部变量示例 gt gt gt def spam def eggs global b print b b 1000 b 100 对eggs 而言是非局部变量 eggs gt gt gt b 10 gt gt gt spam 10 gt gt gt b 1000 gt gt gt def spam def eggs nonlocal b b 1000 b 100 对eggs 而言是非局部变量 eggs print b gt gt gt b 10 gt gt gt spam 1000 gt gt gt b 10 函数的形式参数缺省值的持久性示例 gt gt gt def f a L L append a return L gt gt gt print f 1 1 gt gt gt print f 2 1 2 gt gt gt print f 3 1 2 3 函数的形式参数缺省值的定义示例 gt gt gt from inspect import getfullargspec gt gt gt def func p1 p2 p3 x p4 pass gt gt gt getfullargspec func FullArgSpec args p1 p2 p3 varargs None varkw None defaults x kwonlyargs p4 kwonlydefaults None annotations 函数的可变参数的定义示例 gt gt gt from inspect import getfullargspec gt gt gt def func p1 p2 args p3 kwargs pass gt gt gt 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 a href E7 B6 AD E4 BA AC E4 BA BA html title 維京人 viking a a href E5 89 AF E6 AD 8C html title 副歌 chorus a 修饰后的menu item将原来定义运行3次 gt gt gt 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 Monty Python 结果为 gt gt gt black knight I m invincible My favourite colour is blue None shall pass 调用函数使用帮助信息示例 比如 gt gt gt def randint a b Return random integer in range a b including both end points gt gt gt 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 gt bool pass 对象的方法示例 gt gt gt class Fish object hungry True def eat self food if food is not None self hungry False gt gt gt def status self print Hungray if self hungry else Not hungray gt gt gt e Fish gt gt gt status e Hungray gt gt gt Fish hungry False gt gt gt from types import MethodType gt gt gt e status MethodType status e gt gt gt e status Not hungray gt gt gt Fish hungry True gt gt gt Fish status status gt gt gt f Fish gt gt gt Fish status f Hungray gt gt gt f eat earthworm gt gt gt f status Not hungray 特殊方法和子类调用超类方法的例子 gt gt gt 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 gt gt gt class Advice Thought def message self super Advice self message 警告 日历里的日期比它们看起来更近 gt gt gt t Thought 我是类型Thought的新对象 gt gt gt t message 我觉得我在平行宇宙中把车停歪了 gt gt gt a Advice 我是类型Thought的子类型的新对象 gt gt gt a message 我觉得我在平行宇宙中把车停歪了 警告 日历里的日期比它们看起来更近 gt gt gt 内省一下 gt gt gt super dict repr getattribute get init new thisclass self self class doc gt gt gt super Advice thisclass dict module message doc cls name gt gt gt super Advice thisclass dict cls name 类型Thought的子类型 gt gt gt super Advice a self dict notion gt gt gt super Advice a self class dict cls name 类型Thought的子类型 gt gt gt super Advice a message 我觉得我在平行宇宙中把车停歪了 gt gt gt super Advice get a message 我觉得我在平行宇宙中把车停歪了 特殊方法 类方法和静态方法 new 示例 gt gt gt from weakref import WeakValueDictionary gt gt gt 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 gt gt gt a ak 1 bk 2 ck 3 gt gt gt d D a dk 4 gt gt gt d ak 1 bk 2 ck 3 dk 4 gt gt gt D load a gt gt gt e D create ck 4 gt gt gt e ak 1 bk 2 ck 4 gt gt gt f D ak 1 bk 2 gt gt gt f ck 3 ak 1 bk 2 ck 3 gt gt gt f ak 1 gt gt gt f ak 5 gt gt gt f ak 5 bk 2 ck 3 gt gt gt len f 3 gt gt gt D count 3 gt gt gt del f gt gt gt D count 2 gt gt gt d weakref in D obj dict valuerefs True 在类中采用数据描述器的示例 gt gt gt 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 gt gt gt class MyClass x RevealAccess 10 var x y 5 gt gt gt m MyClass gt gt gt m x Retrieving var x 10 gt gt gt vars m gt gt gt MyClass dict x val 10 gt gt gt m x 20 Updating var x gt gt gt vars m gt gt gt MyClass dict x val 20 gt gt gt m y 5 gt gt gt vars m gt gt gt m y 5 gt gt gt vars m y 5 在类中调用property 的例子 gt gt gt 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 gt gt gt c C gt gt gt vars c C x None gt gt gt C dict init setx weakref delx x getx doc module dict 上述代码可以采用修饰符进一步的书写为 gt gt gt 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 gt gt gt c C gt gt gt vars c C x None gt gt gt 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 gt gt gt type b lt class main B gt gt gt gt print type B B bases lt class main M gt lt class main A gt gt gt gt print type A A bases lt class main M gt lt class object gt gt gt gt print type M M bases lt class type gt lt class type gt gt gt gt print type c c bases lt class type gt lt class object gt gt gt gt print type r r bases lt class type gt 数学运算示例 比如 gt gt gt def mean seq return sum seq len seq gt gt gt mean 3 4 3 5 gt gt gt import math gt gt gt 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日 英語 引文格式1维护 未识别语文类型 link 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 RustPython 2022 03 04 原始内容存档于2022 04 24 Starlark Language 25 May 2019 原始内容存档于2020 06 15 9 0 9 1 9 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 12 0 12 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 14 0 14 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 25 0 25 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 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 48 0 48 1 48 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 51 0 51 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 62 0 62 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 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 and free 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 68 0 68 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 78 0 78 1 9 6 Private Variables 2020 09 27 原始内容存档于2012 10 23 79 0 79 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 92 0 92 1 92 2 Python org Modules 2020 10 30 原始内容存档于2021 02 06 93 0 93 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 98 0 98 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 amp 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 106 0 106 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 Pyston lite our Python JIT as an extension module 2022 08 29 原始内容存档于2022 08 29 This current release only supports Python 3 8 but since Pyston lite has a much smaller surface area we believe we can target multiple releases unlike Pyston which will only target a single release for the foreseeable future 141 0 141 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 149 0 149 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 amp 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 Thread pool Controls Plotly js Open source JavaScript charting library behind Plotly and Dash Dash Analytical Web Apps for Python R Julia and Jupyter Streamlit The fastest way to build data apps in Python Panel A high level app and dashboarding solution for Python Voila Voila turns Jupyter notebooks into standalone web applications Dashboarding tools 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 Mars is a tensor based unified framework for large scale data computation which scales numpy pandas scikit learn and Python functions 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 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 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 参閲 编辑 计算机程序设计主题 自由软件主题 编程语言列表 Python語法及語義 Python的歷史 Python软件列表 英语 List of Python software 外部連接 编辑从维基百科的姊妹计划了解更多有关 Python 的内容 维基共享资源上的多媒体资源 维基语录上的名言 维基教科书上的教科书和手册 维基学院上的學習资源官方网站 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 页面存档备份 存于互联网档案馆 取自 https zh wikipedia org w index php title Python amp oldid 75194016, 维基百科,wiki,书籍,书籍,图书馆,

文章

,阅读,下载,免费,免费下载,mp3,视频,mp4,3gp, jpg,jpeg,gif,png,图片,音乐,歌曲,电影,书籍,游戏,游戏。