TableOfContents

Python语言介绍

1. 总览

Python是一种解释型的编程语言,由Guido van Rossum于1990年创造。Python是完全动态类型的语言,使用自动的内存管理;在这方面它和Perl、Ruby、Scheme、Smalltalk和Tcl语言是类似的。Python是由开放源代码项目开发,由非盈利性组织Python软件基金会(Python Software Foundation)管理,并在项目网站上免费开放。Python 2.4.3版于2006年3月29日发布。

编程范式:

多范式

出现时间:

1990

设计者:

Guido van Rossum

开发者:

Python Software Foundation

最新版本:

2.4.3 / March 29, 2006

类型规则:

强类型,动态类型(鸭子类型)

主要的实现版本:

CPython, Jython, IronPython, PyPy

受哪些语言影响:

ABC, Modula-3, Icon, C, Perl, Lisp, Smalltalk, Tcl

影响了哪些语言:

Ruby, Boo

操作系统:

跨平台

许可证:

Python Software Foundation License

网站:

www.python.org

2. Python设计哲学

Python是一种多范式的语言。也就是说,它不强制编程人员采用某一种特定的编程范式,而是允许多种范式。对于面向对象程序设计(OOP)、结构化程序设计、函数式程序设计(FP)以及面向侧面的程序设计(AOP),它都可以支持。其它的编程模式也可以通过一些扩展来支持,比如通过pyDBC和Contracts for Python可以支持契约式设计(Design by Contract)。Python使用动态类型检查,并使用垃圾收集来进行内存管理。Python一个重要的特性是动态名字解析,即它会在运行时对方法和变量名进行绑定。

在提供多种编程方法的选择的同时,Python的设计者拒绝像Perl那样使用过多过杂乱的语法,而是采用了少而清晰的语法。和Perl一样,Python的开发人员明确的提炼出一种特别的"文化"或者观念,这种文化或观念来自于他们对于语言的期望,这种文化带来一种他们认为是"漂亮"、"明确"和"简单"的语言形式。Perl用户和Python用户最大的区别在于他们对于这些词语的解释不同,以及它们如何被最好的实现(参见TIMTOWTDI和Python哲学)。

Another important goal of the Python developers is making Python fun to use. This is reflected in the origin of the name (after the television series Monty Python's Flying Circus), in the common practice of using Monty Python references in example code, and in an occasionally playful approach to tutorials and reference materials. For example, the metasyntactic variables often used in Python literature are spam and eggs, instead of the traditional foo and bar.

Python开发人员另一个重要的目标是让Python用起来尽量有趣。这反映在Python的名字的由来上(由Monty Python的飞行马戏团的系列电视节目命名),也反映在示例代码中使用Monty Python上,也反映在入门和参考材料中偶尔出现的玩笑式的方法上。比如说,在解释有关语法没有实际含义的变量名字上,Python经常使用spam和eggs,而不是传统的foo和bar。

Python is sometimes referred to as a "scripting language". In practice, it is used as a dynamic programming language for both application development and occasional scripting. Python has been used to develop many large software projects such as the Zope application server and the Mnet and BitTorrent file sharing systems. It is also extensively used by Google.

Python有时候被称作"脚本语言"。实际上,作为一种动态的编程语言,它既用于应用开发,偶尔也用于脚本开发。Python已经被用于开发很多大型的软件项目,比如说Zope应用服务器,和Mnet、BitTorrent文件共享系统。它也被Google广泛使用。

Another important goal of the language is ease of extensibility. New built-in modules are easily written in C or C++. Python can also be used as an extension language for existing modules and applications that need a programmable interface.

这个语言的另一个重要目标是易扩展性。新的内置模块可以很容易用C或者C++写成。对于现有的需要一个可编程接口的模块或者应用程序,Python也可以作为它们的一个扩展语言来使用。

Though the design of Python is somewhat hostile to functional programming (no tail call elimination or good support for anonymous closures) and the Lisp tradition, there are significant parallels between the philosophy of Python and that of minimalist Lisp-family languages such as Scheme. Many past Lisp programmers have found Python appealing for this reason.

虽然Python的设计时有些反对函数式编程(没有尾递归消除和好的匿名closure的支持)和Lisp习惯,但是Python的哲学和一些Lisp家族的最小化语言(比如Scheme)的哲学有很多重要的类似之处。很多曾经的Lisp程序员发现Python在这方面是很有吸引力的。

The Zen of Python by TimPeters: Python之道:

  1. Beautiful is better than ugly. 美比丑好。
  2. Explicit is better than implicit. 直言不讳比心照不宣好。
  3. Simple is better than complex. 简单比内部复杂更好。
  4. Complex is better than complicated. 内部复杂比外部复杂好。
  5. Flat is better than nested. 平面的比嵌套的好
  6. Sparse is better than dense. 错落有致比密密匝匝的好
  7. Readability counts. 可读性很重要
  8. Special cases aren't special enough to break the rules. 特殊情况不能特殊到打破规律
  9. Although practicality beats purity. 虽然实用比纯粹更重要
  10. Errors should never pass silently. 永远别让错误悄悄地溜走
  11. Unless explicitly silenced. 除非是你故意的
  12. In the face of ambiguity, refuse the temptation to guess. 碰到模棱两可的地方,绝对不要去作猜测
  13. There should be one-- and preferably only one --obvious way to do it. 什么事情都应该有一个,而且最好只有一个显而易见的解决办法
  14. Although that way may not be obvious at first unless you're Dutch. 虽然刚开始的时候,这个办法可能不是那么的显而易见,但谁叫你不是荷兰人
  15. Now is better than never. 现在就开始要比永远都不做要好。
  16. Although never is often better than *right* now. 虽然很多时候永远都不做要比匆匆忙忙去做要好。
  17. If the implementation is hard to explain, it's a bad idea. 如果一个想法实现起来很困难,那它本身就不是一个好想法
  18. If the implementation is easy to explain, it may be a good idea. 如果一个想法实现起来很容易,那它或许就是一个好想法
  19. NameSpaces are one honking great idea -- let's do more of those! 名字空间是个了不起的想法,所以我们现在就开始吧

If you have Python 2.1.2 or later you can read the Philosophy of Python whenever you want. Just do the following:

如果你使用2.1.2版或者更新的Python,你在任何时候都可以使用如下命令来阅读Python的哲学:

 $ python
 Python 2.2 (#1, Apr 17 2002, 16:11:12) 
 [GCC 2.95.2 19991024 (release)] on some-os
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import this

3. duck typing 鸭子类型

In computer science, duck typing is a term for dynamic typing typical of some programming languages, such as Smalltalk or Visual FoxPro, where a variable's value itself determines what the variable can do. It also implies that an object is interchangeable with any other object that implements the same interface, regardless of whether the objects have a related inheritance hierarchy.

在计算机科学中,鸭子类型是一个描述某些语言(比如Smalltalk、Visual Foxpro等)中的动态类型系统的名词。在这些语言中,变量的值决定了这个变量能够做什么。这意味着,一个对象和其它任何一个实现同样接口的对象都是可以互换的,而不管这些对象是不是有继承关系。

The term is a reference to the "duck test"—"If it walks like a duck and quacks like a duck, it must be a duck." One can also say that the duck typing method ducks the issue of typing variables.

这个名词源自"鸭子测试":"如果一个东西像鸭子一样走路,像鸭子一样叫,那么它一定就是鸭子。"One can also say that the duck typing method ducks the issue of typing variables.

Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs hasattr() tests or EAFP [Easier to Ask Forgiveness than Permission] programming.

Pythonic编程风格,通过观查一个对象的方法或属性特征,而不是一个对象和某种类型的显式关系来决定一个对象的类型("如果一个东西像鸭子一样走路,像鸭子一样叫,那么它一定就是鸭子。")。通过注重接口而不是某种类型,良好设计的代码通过多态来提高了灵活性。鸭子类型避免使用type()和isinstance()。取而代之的是,它使用hasattr()来测试或者EAFP(Easier to Ask Forgiveness than Permission)编程。

The standard example of duck typing in Python is file-like classes. Classes can implement some or all of the methods of file and can be used where file would normally be used. For example, GzipFile implements a file-like object for accessing gzip-compressed data. cStringIO allows treating a Python string as a file. Sockets and files share many of the same methods as well. However, sockets lack the tell() method and cannot be used everywhere that GzipFile can be used. This shows the flexibility of duck typing: a file-like object can implement only methods it is able to, and consequently it can be only used in situations where it makes sense.

Python中鸭子类型的标准例子是类似file的类。类可以实现一部分或者全部file的方法,然后可以用在file原来可以使用的地方。比如说,GzipFile实现了类似file的对象来访问gzip压缩的数据。cStringIO允许将一个Python字符串作为文件来处理。Sockets和files也有很多相同的方法。然而,socket缺少tell(),不能要在任何GzipFile可以使用的地方。这说明鸭子类型的一个灵活性:一个类似file的对象可以只实现它能够实现的方法,这使它只能够用在合理的地方。

4. 新名词Pythonic

A few neologisms have come into common use within the Python community. One of the most common is "pythonic", which can have a wide range of meanings related to program style. To say that a piece of code is pythonic is to say that it uses Python idioms well; that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms; that its use meshes well with the rest of the language.

In contrast, a mark of unpythonic code is that it attempts to "write C++ (or Lisp, or Perl) code in Python"—that is, provides a rough transcription rather than an idiomatic translation of forms from another language.

The prefix Py- can be used to show that something is related to Python. Examples of the use of this prefix in names of Python applications or libraries include Pygame, a binding of SDL to Python (commonly used to create games), PyUI, a GUI encoded entirely in Python, and PySol, a series of solitaire card games programmed in Python.

Users and admirers of Python—most especially those considered knowledgeable or experienced—are often referred to as Pythonists, Pythonistas, and Pythoneers

5. 历史

5.1. Python 1

Python语言作为ABC程序设计语言的后继,最早在20世纪90年代早期由Guido van Rossum在CWI创造。van Rossum是Python的主要作者,并一直担任决定Python发展方向的主要角色,因此他也被戏称为Python的仁慈的命运主宰者。

在CWI发布的最后版本是Python 1.2。在1995年,Guido转移到Virginia洲的Reston市的Corporation for National Research Initiatives (CNRI)继续他的Python工作。在那里发布了Python的好几个版本。Python 1.6是CNRI发布的最后版本。

在Python 1.6发布以后,Guido van Rossum离开CNRI,去和一些商业软件开发人员一起工作。这时,让Python能够在GPL发布的软件中使用,成了人们迫切的愿望。CNRI和Free Software Foundation(FSF)取得了沟通,并修改了Python的自由软件许可证,使其和GPL能够兼容。那一年,Guido获得了FSF的Advancement of Free Software大奖。

Python 1.6.1和Python 1.6基本上相同,只有一些小的bug的修正,并带有新的GPL兼容的许可证。

5.2. Python 2

在2000年,Guido和Python核心开发团队转移到了BeOpen.com,组成了BeOpen PythonLabs团队。Python 2.0是第一个也是唯一一个在BeOpen.com发布的版本。在Python 2.0发布以后,Guido van Rossum和其他PythonLabs开发人员加入了Digital Creations。

Python 2.1继续了Python 1.6.1和Python 2.0的工作。它的许可证改名为Python Software Foundation License。所有从Python 2.1 alpha版开始增加的知识产权,归Python Software Foundation(PSF)所有。这是一个模仿Apache Software Foundation模式的非盈利性组织。

5.3. 未来

Python开发人员一直在讨论Python的未来版本Python 3.0(这个项目被称作"Python 3000"或"Py3K")。它将会打破对2.x系列的向后兼容性,来修正语言中存在的一些已知的缺陷。指导原则是"通过去除老的解决问题的方法,来减少重复的语言特性"。现在还没有Python 3.0的确定的时间表,但是一个PEP(Python Enhancement Proposal)中详细描述了计划要改变的东西。

计划要改变的东西包括:

6. Python语法特点

Python被设计成具有高度可读性的语言。它努力使代码看上去布局整齐,更多的使用英语单词来代替其他语言中的标点符号,并且它的语法结构比其他结构化语言(比如C、Perl或者Pascal)少得多。

6.1. 缩进

Python使用缩进而不是一对花括号来划分语句块。对某些特定语句后面的语句增加缩进量(来表示语句块的开始);用减少缩进量来表示当前语句块的结束。

6.2. 语句

Python的语句包括:

每个语句都有它自己的语义:比如说,def语句和其他很多语句不同,它不会马上执行它附属的语句块,

6.3. 基本数据类型

Python包括一组不同的数据类型。其中最常用的是:

这里并没有列出全部类型,Python中还有很多其他类型。而以上这些是最常用的部分。

7. Python支持的平台

运行Python最流行的平台(因此也是维护得最好的平台)是Linux、BSD、Mac OS X和Microsoft Windows。此外,在Java平台上和.Net Framework(或者Mono)上也有一些独立开发的Python的实现,分别称作Jython和IronPython。其他支持的平台包括:

类Unix系统

桌面操作系统

特殊的和嵌入式的系统

大型机和其他系统

Python的大部分第三方库(甚至部分官方库)只支持Windows、Linux、BSD和Mac OS X。

Python最早是作为Amoeba操作系统上一种能够进行系统调用的脚本语言开发的;然而那个版本现在不再维护了。

8. Python应用领域

Python is used in a wide variety of application domains, including web and internet, database, desktop GUIs, scientific and numeric computation, education, network programming, software build and testing, and game development and 3D rendering, among others.

8.1. 网页与因特网开发

Python offers a wide range of choices for web development including high-end solutions such as Zope, mega frameworks such as Django and TurboGears, and advanced content management systems such as Plone and CPS. Python is also great for CGI.

Python's extensive support for XML, email, RSS feeds, and many other Internet protocols makes Python a great choice for developing custom web solutions and other internet-based applications.

8.2. 数据库访问

Need to access a database? Custom and ODBC interfaces to MySQL, Oracle, MS SQL Server, PostgreSQL, SybODBC, and others are available for free download.

8.3. 桌面图形界面

Python arrives on your hard drive with the Tk GUI development library. Third-party libraries are available for MFC (via win32 extensions), wxWidgets, GTK, Qt, Delphi, and more. Scientific and Numeric

Python is widely used in scientific and numeric computing, including in Bioinformatics (see also Python course in Bioinformatics) and Physics, among others.

8.4. 教育

Python is a superb language for teaching programming, both at the introductory level and for more advanced courses. The Education Special Interest Group is a good place to start. See also pyBiblio and the Software Carpentry Course (funded by the Python Software Foundation).

8.5. 网络编程

In addition to web and internet support described above, Python also provides support for lower level network programming with its easy to use sockets implementation and with powerful third party modules such as Twisted, a framework for asyncronous network programming,

8.6. 软件开发

Python is often used as a support language for software developers, for build control and management, testing, and in many other ways. Some of the development support tools written in Python include SCons for build control, Buildbot and Apache Gump for automated continuous compilation and testing, and Trac for bug tracking and project management.

See also the list of Integrated Development Environments available for Python and the Python Package Index, which hosts thousands of third party modules for Python.

8.7. 游戏和三维图形

Python is widely used in commercial and hobby game development (some of which are listed on the Python Games wiki page). PyGame and PyKyra are two of the game frameworks available for Python. There are also a number of 3D rendering libraries available for Python.

9. Python应用实例

The Python programming language is actively used in industry and academia for a wide variety of purposes.

9.1. Python的教育用途

As of 2005, Python is getting more popular for teaching computer programming. Its strengths for teaching include its syntactic simplicity, flexible typing, and interactive interpreter.

Python uses far fewer symbols than languages like Java and C. For example blocks inside loops and IF statements are indicated by indentation rather than curly braces ({}), and the end of a line does not have to have a semicolon. Beginning students often have initial trouble with memorizing where curly braces and semi-colons go. With Python students can skip directly to the fun part of writing code that does something. Similarly, with Java, and C++, variables types must be declared before being used. That is not needed in Python which again allows students to quickly get to the interesting part of getting their program to do something.

The interactive interpreter is an extremely valuable aid to learning and experimentation. Learning-by-doing is about trying things out and seeing what happens. The faster you can get results from your experiment, the faster that learning produces results. Experience has shown that the interactive interpreter and lack of a compiler really speeds up the learning process, both for beginners and for pros who are learning a new library and such.

9.2. 使用Python的大型组织

9.3. 使用Python写成的软件

9.4. Python包

The Python Cheese Shop and Vaults of Parnassus are two primary directories of hundreds of Python packages

See more recommended modules at Useful Modules in the Python.org wiki.

9.5. Python软件目录

10. Python的实现

The standard Python interpreter also supports an interactive mode in which it acts as a kind of shell: expressions can be entered one at a time, and the result of their evaluation is seen immediately. This is a boon for those learning the language and experienced developers alike: snippets of code can be tested in interactive mode before integrating them into a proper program. As well, the Python shell is often used to interactively perform system tasks, such as modifying files.

Python also includes a unit testing framework for creating exhaustive test suites. While static typing aficionados see this as a replacement for a static type-checking system, Python programmers largely do not share this view.

Standard Python does not support continuations, and according to Guido van Rossum, never will. However, better support for coroutine-like functionality is planned, by extending Python's generators [3]

11. Python的标准库

Python has a large standard library, which makes it well suited to many tasks. This comes from a so-called "batteries included" philosophy for Python modules. The modules of the standard library can be augmented with custom modules written in either C or Python. The standard library is particularly well tailored to writing Internet-facing applications, with a large number of standard formats and protocols (such as MIME and HTTP) supported. Modules for creating graphical user interfaces, connecting to relational databases, arithmetic with arbitrarily precise decimals, and manipulating regular expressions are also included.

The standard library is one of Python's greatest strengths. The bulk of it is cross-platform compatible, meaning that even heavily leveraged Python programs can often run on Unix, Windows, Macintosh, and other platforms without change.

It is currently being debated whether or not third-party but open source Python modules such as Twisted, NumPy, or wxPython should be included in the standard library, in accordance with the batteries included philosophy.

ch3n2k.com | Copyright (c) 2004-2020 czk.