版本46和210间的区别 (跳过第164版)
于2006-06-11 11:50:53修订的的版本46
大小: 48109
编辑: czk
备注:
于2020-06-05 17:09:32修订的的版本210
大小: 12851
编辑: czk
备注:
删除的内容标记成这样。 加入的内容标记成这样。
行号 1: 行号 1:
[[TableOfContents]]
= Python语言简介 =

== 总览 ==

Python is an interpreted programming language created by Guido van Rossum in 1990. Python is fully dynamically typed and uses automatic memory management; it is thus similar to Perl, Ruby, Scheme, Smalltalk, and Tcl. Python is developed as an open source project, managed by the non-profit Python Software Foundation, and is available for free from the project website. Python 2.4.3 was released on March 29, 2006.

||Paradigm编程范式:||Multi-paradigm多范式||
||Appeared in出现时间:||1990||
||Designed by设计者:||Guido van Rossum||
||Developer开发者:||Python Software Foundation||
||Latest release最后发布时间:||2.4.3 / March 29, 2006||
||Typing discipline类型规则:||Strong, dynamic ("duck")||
||Major implementations主要实现:||CPython, Jython, IronPython, PyPy||
||Influenced by受哪些语言影响:||ABC, Modula-3, Icon, C, Perl, Lisp, Smalltalk, Tcl||
||Influenced影响了哪些语言:||Ruby, Boo||
||OS操作系统:||Cross-platform||
||License许可证:||Python Software Foundation License||
||Website网站:||www.python.org||

== Python设计哲学 ==

Python is a multi-paradigm language. This means that, rather than forcing coders to adopt one particular style of coding, it permits several. Object orientation, structured programming, functional programming, and aspect-oriented programming are all supported. Other paradigms can be supported through extensions, such as pyDBC and Contracts for Python which allow Design by Contract. Python is dynamically type-checked and uses garbage collection for memory management. An important feature of Python is dynamic name resolution, which binds method and variable names during program execution.

While offering choice in coding methodology, Python's designers reject exuberant syntax, such as in Perl, in favor of a sparser, less cluttered one. As with Perl, Python's developers expressly promote a particular "culture" or ideology based on what they want the language to be, favoring language forms they see as "beautiful", "explicit" and "simple". For the most part, Perl and Python users differ in their interpretation of these terms and how they are best implemented (see TIMTOWTDI and PythonPhilosophy).

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 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. [1]

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.

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.

The Zen of Python by TimPeters:

 1. Beautiful is better than ugly.
 1. Explicit is better than implicit.
 1. Simple is better than complex.
 1. Complex is better than complicated.
 1. Flat is better than nested.
 1. Sparse is better than dense.
 1. Readability counts.
 1. Special cases aren't special enough to break the rules.
 1. Although practicality beats purity.
 1. Errors should never pass silently.
 1. Unless explicitly silenced.
 1. In the face of ambiguity, refuse the temptation to guess.
 1. There should be one-- and preferably only one --obvious way to do it.
 1. Although that way may not be obvious at first unless you're Dutch.
 1. Now is better than never.
 1. Although never is often better than right now.
 1. If the implementation is hard to explain, it's a bad idea.
 1. If the implementation is easy to explain, it may be a good idea.
 1. 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:
{{{
 $ 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
}}}

== 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.

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.

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.

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.



== 新名词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

== History ==
=== Python 1 ===

Python was created in the early 1990s by Guido van Rossum at CWI in the Netherlands as a successor of the ABC programming language. van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is jokingly acknowledged by referring to him as its Benevolent Dictator for Life (BDFL).

The last version released from CWI was Python 1.2. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI) in Reston, Virginia where he released several versions of the software. Python 1.6 was the last of the versions released by CNRI.

Following the release of Python 1.6, and after Guido van Rossum left CNRI to work with commercial software developers, it became clear that the ability to use Python with software available under the GPL was very desirable. CNRI and the Free Software Foundation (FSF) interacted to develop enabling wording changes to the Python's free software license that would make it GPL-compatible. That year, Guido was awarded the FSF Award for the Advancement of Free Software.

Python 1.6.1 is essentially the same as Python 1.6, with a few minor bug fixes, and with the new GPL-compatible license.

=== Python 2 ===

In 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. Python 2.0 was the first and only release from BeOpen.com. After Python 2.0 was released by BeOpen.com, Guido van Rossum and the other PythonLabs developers joined Digital Creations.

Python 2.1 was a derivative work of Python 1.6.1, as well as of Python 2.0. Its license was renamed Python Software Foundation License. All intellectual property added, from the time of Python 2.1's alpha release on, is owned by the Python Software Foundation (PSF), a non-profit organization modeled after the Apache Software Foundation.

=== The future ===

Python developers have an ongoing discussion of a future version called Python 3.0 (the project is called "Python 3000" or "Py3K") that will break backwards compatibility with the 2.x series in order to repair perceived flaws in the language. The guiding principle is to "reduce feature duplication by removing old ways of doing things". There is no definite schedule for Python 3.0, but a PEP (Python Enhancement Proposal) that details planned changes exists. [2]

Planned changes include:

    * move map, filter and reduce out of the built-in namespace (the rationale being that map and filter are expressed more clearly as list comprehensions, and reduce more clearly as an accumulation loop)
    * add support for optional type declarations
    * unify the str/unicode types, and introduce a separate mutable bytes type
    * convert built-ins to returning iterators (instead of lists), where appropriate
    * remove backwards-compatibily features like classic classes, classic division, string exceptions, implicit relative imports

== Python语法特点 ==

Python was designed to be a highly readable language. It aims toward an uncluttered visual layout, uses English keywords frequently where other languages use punctuation, and has notably fewer syntactic constructions than many structured languages such as C, Perl, or Pascal.

=== Indentation ===

Python uses indentation, rather than curly braces, to delimit blocks. An increase in indentation comes after certain statements; a decrease in indentation signifies the end of the current block.

=== Statements ===

Python's statements include:

    * if statement, for conditionally executing blocks of code, along with else and elif (a contraction of else-if).
    * The while statement runs a block of code until a condition is False.
    * for loops iterate over an iterable, capturing each element to a local variable for use by the attached block.
    * class statements execute a block of code and attach its local namespace to a class, for use in object oriented programming.
    * def defines a function.

Each statement has its own semantics: for example, the def statement does not execute its block immediately, unlike most other statements.

=== Fundamental datatypes ===

Python includes a number of different datatypes. Amongst the most used are:

    * list — a mutable sequence.
    * str — an immutable sequence of characters.
    * dict — a dictionary.
    * set — an approximation of a mathematical set (an unordered collection, where each element can only appear once).

This list is not exhaustive; there are many other types provided by Python - these are merely some of the most commonly used.

== Python支持的平台 ==

The most popular (and therefore best maintained) platforms Python runs on are Linux, BSD, Mac OS X, Microsoft Windows. Separate implementations also exist for the Java (called Jython) and for the .NET Framework or Mono (called IronPython). Other supported platforms include:

Unix-like

    * AIX operating system
    * BSD
    * FreeBSD
    * NetBSD
    * Linux
    * OpenBSD
    * SPARC Solaris
    * Other Unixes, e.g. Irix

 

Desktop OS's

    * Amiga
    * AROS
    * BeOS
    * Mac OS 9
    * Mac OS X
    * Microsoft Windows
    * OS/2
    * RISC OS (formerly Acorn)

 

Special and embedded

    * GP2X
    * Java virtual machine
    * Nokia 770 Internet Tablet
    * Palm OS
    * PlayStation 2
    * PlayStation Portable
    * Psion
    * QNX
    * Sharp Zaurus
    * Symbian OS
    * Windows CE/Pocket PC
    * Xbox (Used in XBMC)
    * VxWorks

 

Mainframe and other

    * AS/400
    * OS/390
    * Plan 9 from Bell Labs
    * VMS
    * z/OS

Most of the third-party libraries for Python (and even some first-party ones) are only available on Windows, Linux, BSD, and Mac OS X.

Python was originally developed as a scripting language for the Amoeba operating system capable of making system calls; however, that version is no longer maintained.

== Python应用 ==

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

=== 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.

=== 使用Python的大型组织 ===

    * Google uses Python for many tasks including the backends of web apps such as Gmail and Google Maps and for many of its search-engine internals.
    * NASA is using Python to implement a CAD/CAE/PDM repository and model management, integration, and transformation system which will be the core infrastructure for its next generation collaborative engineering environment.

=== 使用Python写成的软件 ===

    * BitTorrent, the original implementation and several derivatives
    * Chandler, a personal information manager including calendar, email, tasks and notes support that is currently under development
    * Civilization IV videogame and the newly released computer game uses boost.python to allow the Python programming language access to many parts of the game (including the style and content of all interface screens)
    * Mailman, one of the more popular packages for running email mailing lists
    * Kombilo, go games' database manager and browser.
    * MoinMoin, a popular wiki engine in Python
    * OpenRPG, a virtual table on which to play Role Playing Games over the internet
    * Plone, a user-friendly and powerful open source Content Management System
    * Portage, the heart of Gentoo Linux. An advanced package management system based on the *BSD style ports system
    * Solipsis, a system for massively shared virtual world
    * Trac, bug/issue tracking database, integrated with MoinMoin wiki and Subversion source version control
    * Turbogears, an application framework composed of Cherrypy, SQLObject, MochiKit, and KID templates
    * Vampire: The Masquerade - Bloodlines, a videogame, uses Python for game scripting
    * ViewVC, a web-based interface for browsing CVS and SVN repositories
    * Zope, an object-oriented web-application platform. Zope includes an application server with an integrated object-oriented database and a built-in web-based management interface
    * Battlefield 2, a first person shooter that uses python for its configuration scripts
    * Indian Ocean Tsunami Detector, a free mobile phone software for tsunami prediction.
    * EVE Online, a space Multi Massive Online Role Playing Game, the highest-ranked MMORPG on MMORPG.com
    * SPE - Stani's Python Editor, a free, open-source Python IDE for Windows, Linux & Mac with wxGlade (GUI designer), PyChecker (Code Doctor) and Blender (3D) support.

=== Python包 ===

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

    * matplotlib, an extension providing matlab-like plotting and mathematical functions
    * Numeric Python, a language extension that adds support for large, multi-dimensional arrays and matrices
    * SciPy, a library of scientific and numerical routines
    * SimPy, a discrete-event simulation package;
    * Biopython, an international association of developers of freely available Python tools for computational molecular biology.
    * PyOpenGL, a package that allows 3D rendering using Python
    * Soya 3D, a high-level 3D game engine for Python
    * Pygame http://www.pygame.org Python game development
    * Python Imaging Library, a module for working with images
    * PyGTK, http://www.pygtk.org/, a popular cross-platform GUI library based on GTK+; furthermore, other GNOME libraries also have bindings for Python
    * PyQt, another popular cross-platform GUI library based on Qt; as above, KDE libraries have bindings too
    * wxPython, a port of wxWidgets and a popular cross-platform GUI library for Python

    * PyObjC, a Python-Objective C bridge that allows one to write Mac OS X software in Python
    * py2exe, compiler that turns Python scripts into standalone Windows programs

    * CherryPy, a Python-powered web framework
    * Django, another Python-powered web framework
    * Topsite Templating System, another Python-powered web framework
    * TurboGears, a web framework combining CherryPy, SQLObject, and Kid
    * ZODB a Python-specific object-oriented database
    * Cheetah, a Python-powered template engine and code-generation tool
    * mod_python, an Apache module allowing direct integration of Python scripts with the Apache web server
    * Quixote (software) a framework for developing Web applications in Python
    * Twisted, a networking framework for Python

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

=== 软件目录 ===

    * Python Cheese Shop (also called the Python Package Index or PyPI) is the official directory of Python software libraries and modules.
    * ActiveState O'Reilly Python Cookbook contains hunderds of code samples for various tasks using Python.
    * Python Projects and Modules lots of useful code, as well as several articles on Python Programming.
    * Vaults of Parnassus — Links to resources.
    * Python 3D Software Collection — pointers to packages specifically useful in the production of 3D software and/or games with Python

== 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]

    * Python – The reference implementation, also known as CPython
    * Jython – Python coded in Java
    * IronPython – Python for .NET and Mono platforms
    * Boo – Python-based but with static typing, for .NET and Mono
    * Stackless Python - Python with coroutines
    * Psyco - not an implementation, but JIT compiler for CPython
    * PyPy – Python coded in Python
    * Parrot – Virtual machine being developed mainly as the runtime for Perl 6, but with the intent to also support dynamic languages like Python, Ruby, Tcl, etc. Can currently execute a subset of Python
    * Logix – Python alternate front-end with macros
    * Movable Python- An alternative distribution of CPython for Windows. It can run off a USB stick and provides a Portable Programming Environment.

== 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.

== Python学习资料 ==
 * [http://www.python.org/ Python官方站点]
 * [http://python.cn/ Python中文社区]
 * [https://secure.wikimedia.org/wikipedia/en/wiki/Python_programming_language Wikipedia:Python_programming_language] [https://secure.wikimedia.org/wikipedia/zh/wiki/Python Wikipedia上的Python编程语言]
 * [http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html One Day of IDLE Toying] [http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE-chinese.htm 摆弄一天IDLE]
 * [http://www.ibiblio.org/obp/thinkCSpy/ How to Think Like a Computer Scientist (Learning with Python)]
 * [http://diveintopython.org/ Dive Into Python] [http://www.woodpecker.org.cn/obp/diveintopython-zh-5.4/zh-cn/dist/html/toc/index.html dive into python最新中文版]
 * [http://www-128.ibm.com/developerworks/cn/linux/theme/special/index.html#python ibm上的python专题]
 * [http://groups.google.com/group/comp.lang.python Python讨论组comp.lang.python]
 * [http://pine.fm/LearnToProgram/ Learn to Program(ruby)]

= Python语法 =

The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted (by both the runtime system and by human readers). Python was designed to be a highly readable language. It aims toward an uncluttered visual layout, uses English keywords frequently where other languages use punctuation, and has notably fewer syntactic constructions than many structured languages such as C, Perl, or Pascal. A program that does not conform to these rules will not run, or it will produce unexpected results.

== Indentation ==

One oft noted element of Python's syntax is its use of whitespace to delimit program blocks (the off-side rule). Sometimes termed "the whitespace thing", it is one aspect of Python syntax that many programmers otherwise unfamiliar with Python have heard of, since it is unusual among most commonly used programming languages.

In so-called "free-format" languages, that use the block structure ultimately derived from ALGOL, blocks of code are set off with braces ({ }) or keywords. In all these languages, however, programmers conventionally indent the code within a block, to set it off visually from the surrounding code.

Python, instead, borrows a feature from its predecessor ABC — instead of punctuation or keywords, it uses this indentation itself to indicate the run of a block. A brief example will make this clear.

Here are C and Python recursive functions which do the same thing—computing the factorial of an integer:

Factorial function in C:
{{{#!cplusplus
int factorial(int x)
{
    if (x == 0) {
        return 1;
    }
    else {
        return x * factorial(x-1);
    }
}
}}}
Factorial function in Python:
{{{#!python
def factorial(x):
    if x == 0:
        return 1
    else:
        return x * factorial(x-1)
}}}
Some programmers used to ALGOL-style languages, in which whitespace is semantically empty, find this confusing or even offensive. A few have drawn an unflattering comparison to the column-oriented style used on punched-card Fortran systems. When ALGOL was new, it was a major development to have "free-form" languages in which only symbols mattered and not their position on the line.

To Python programmers, however, "the whitespace thing" is simply the enforcement of a convention that programmers in ALGOL-style languages already follow anyway. They also point out that the free-form syntax has the disadvantage that, since indentation is ignored, good indentation cannot be enforced. Thus, incorrectly indented code may be misleading, since a human reader and a compiler could interpret it differently. Here is an example:

Misleading indentation in C:
{{{#!cplusplus
for (i = 0; i < 20; ++i)
   a();
   b();
   c();
}}}

This code is intended to call functions a(), b(), and c() 20 times — and at first glance, that's what it appears to do. However, the interpreted code block is just {a();}. The code calls a() 20 times, and then calls b() and c() one time each. This can be confusing to novice programmers.

The 'whitespace thing' has minor disadvantages. Both space characters and tab characters are currently accepted as forms of indentation. Since they are not visually distinguishable (in many tools), mixing spaces and tabs can create bugs that take specific efforts to find (a perennial suggestion among Python users has been removing tabs as block markers—except, of course, among those Python users who propound removing spaces instead).

Because whitespace is syntactically significant, it is not always possible for a program to automatically correct the indentation in Python code as can be done with C or Lisp code. Moreover, formatting routines which remove whitespace - for instance, many Internet forums — can completely destroy the syntax of a Python program, whereas a program in a bracketed language would merely become more difficult to read. Similarly, it is generally easier for an editing tool to detect and show matching (or mismatched) delimiters in an ALGOL-style language than to help a programmer with his or her Python indentation, and multiple indentation levels can be confusing when a function spans a page boundary.

== Data structures ==

Since Python is a dynamically typed language, Python values, not variables, carry type. This has implications for many aspects of the way the language functions.

All variables in Python hold references to objects, and these references are passed to functions by value; a function cannot change the value a variable references in its calling function. Some people (including Guido van Rossum himself) have called this parameter-passing scheme "Call by object reference."

Among dynamically typed languages, Python is moderately type-checked. Implicit conversion is defined for numeric types, so one may validly multiply a complex number by a long integer (for instance) without explicit casting. However, there is no implicit conversion between (e.g.) numbers and strings; a string is an invalid argument to a mathematical function expecting a number.

=== Base types ===

Python has a broad range of basic data types. Alongside conventional integer and floating point arithmetic, it transparently supports arbitrary-precision arithmetic and complex numbers.

Python supports a panoply of string operations. Strings in Python are immutable, so a string operation such as a substitution of characters, that in other programming languages might alter a string in place, returns a new string in Python. Performance considerations sometimes push for using special techniques in programs that modify strings intensively, such as joining character arrays into strings only as needed.

=== Collection types ===

One of the very useful aspects of Python is the concept of collection (or container) types. In general a collection is an object that contains other objects in a way that is easily referenced or indexed. Collections come in two basic forms: sequences and mappings.

The ordered sequential types are lists (dynamic arrays), tuples, and strings. All sequences are indexed positionally (0 through length − 1) and all but strings can contain any type of object, including multiple types in the same sequence. Both strings and tuples are immutable, making them perfect candidates for dictionary keys (see below). Lists, on the other hand, are mutable; elements can be inserted, deleted, modified, appended, or sorted in-place.

On the other side of the collections coin are mappings, which are unordered types implemented in the form of dictionaries which "map" a set of immutable keys, to corresponding elements much like a mathematical function. The keys in a dictionary must be of an immutable Python type such as an integer or a string. For example, one could define a dictionary having a string "toast" mapped to the integer 42 or vice versa. This is done under the covers via a hash function which makes for faster lookup times, but is also the culprit for a dictionary's lack of order and is the reason mutable objects (i.e. other dictionaries or lists) cannot be used as keys. Dictionaries are also central to the internals of the language as they reside at the core of all Python objects and classes: the mapping between variable names (strings) and the values which the names reference is stored as a dictionary (see Object system). Since these dictionaries are directly accessible (via an object's __dict__ attribute), meta-programming is a straightforward and natural process in Python.

A set collection type was added to the core language in version 2.4. A set is an unindexed, unordered collection that contains no duplicates, and implements set theoretic operations such as union, intersection, difference, symmetric difference, and subset testing. There are two types of sets: set and frozenset, the only difference being that set is mutable and frozenset is immutable. Elements in a set must be hashable and immutable. Thus, for example, a frozenset can be an element of a regular set whereas the opposite is not true.

Python also provides extensive collection manipulating abilities such as built in containment checking and a generic iteration protocol.

=== Object system ===

In Python, everything is an object, even classes. Classes, as objects, have a class, which is known as their metaclass. Python also supports multiple inheritance and mixins (see also MixinsForPython).

The language supports extensive introspection of types and classes. Types can be read and compared— types are instances of type. The attributes of an object can be extracted as a dictionary.

Operators can be overloaded in Python by defining special member functions—for instance, defining __add__ on a class permits one to use the + operator on members of that class.

== Operators ==

=== Comparison operators ===

The basic comparison operators such as ==, <, >=, and so forth, are used on all manner of values. Numbers, strings, sequences, and mappings can all be compared. Although disparate types (such as a str and a int) are defined to have a consistent relative ordering, this is considered a historical design quirk, and will no longer be allowed in Python 3000.

Chained comparison expressions such as a < b < c have roughly the meaning that they have in mathematics, rather than the unusual meaning found in C and similar languages. The terms are evaluated and compared in order. The operation has short-circuit semantics, meaning that evaluation is guaranteed to stop as soon as a verdict is clear: if a < b is false, c is never evaluated as the expression cannot possibly be true anymore.

For expressions without side effects, a < b < c is equivalent to a < b and b < c. However, there is a substantial difference when the expressions have side effects. a < f(x) < b will evaluate f(x) exactly once, whereas a < f(x) and f(x) < b will evaluate it once if the value of a is less than f(x) and twice otherwise.

=== Logical operators ===

Python 2.2 and earlier does not have an explicit boolean type. In all versions of Python, boolean operators treat zero values or empty values such as "", 0, None, 0.0, [], and {} as false, while in general treating non-empty, non-zero values as true. In Python 2.2.1 the boolean constants True and False were added to the language (subclassed from 1 and 0). The binary comparison operators such as == and > return either True or False.

The boolean operators and and or use minimal evaluation. For example, y == 0 or x/y > 100 will never raise a divide-by-zero exception. For backward compatibility, these operators return the value of the last operand evaluated. Thus the expression (4 and 5) evaluates to 5, and (4 or 5) evaluates to 4.

== Functional programming ==

As mentioned above, another strength of Python is the availability of a functional programming style. As may be expected, this makes working with lists and other collections much more straightforward. One such construction is the list comprehension, as seen here in calculating the first five powers of two:
{{{#!python
numbers = [1, 2, 3, 4, 5]
powers_of_two = [2**n for n in numbers]
}}}
The Quicksort algorithm can be expressed elegantly using list comprehensions:
{{{#!python
def qsort(L):
  if L == []: return []
  pivot = L[0]
  return qsort([x for x in L[1:] if x < pivot]) + [pivot] + \
         qsort([y for y in L[1:] if y >= pivot])
}}}
Although execution of this naïve form of Quicksort is less space-efficient than forms which alter the sequence in-place, it is often cited as an example of the expressive power of list comprehensions.

=== First-class functions ===

In Python, functions are first-class objects that can be created and passed around dynamically.

Python's lambda construct can be used to create anonymous functions within expressions. Lambdas are however limited to containing expressions; statements can only be used in named functions created with the def statement. (However, any type of control flow can in principle be implemented within lambda expressions[1] by short-circuiting the and and or operators.)

=== Closures ===

Python has had support for lexical closures since version 2.2. Python's syntax, though, sometimes leads programmers of other languages to think that closures are not supported. Since names are bound locally, the trick to creating a closure is using a mutable container within enclosing scope. Many Python tutorials explain this usage, but it is an atypical style in Python programs.

=== Generators ===

Introduced in Python 2.2 as an optional feature and finalized in version 2.3, generators are Python's mechanism for lazy evaluation of a function that would otherwise return a space-prohibitive or computationally intensive list.

This is an example to lazily generate the prime numbers:
{{{#!python
from itertools import count
def generate_primes(stop_at=None):
    primes = []
    for n in count(2):
        if stop_at is not None and n > stop_at:
            return
        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
}}}

To use this function simply call, e.g.:
{{{#!python
for i in generate_primes(): # iterate over ALL primes
    if i > 100: break
    print i
}}}
The definition of a generator appears identical to that of a function, except the keyword yield is used in place of return. However, a generator is an object with persistent state, which can repeatedly enter and leave the same scope. A generator call can then be used in place of a list, or other structure whose elements will be iterated over. Whenever the for loop in the example requires the next item, the generator is called, and yields the next item.

Generators don't have to be infinite like the prime-number example above. When a generator terminates, an internal exception is raised which indicates to any calling context that there are no more values. A for loop or other iteration will then terminate.

=== Generator expressions ===

Introduced in Python 2.4, generator expressions are the lazy evaluation equivalent of list comprehensions. Using the prime number generator provided in the above section, we might define a lazy, but not quite infinite collection.
{{{#!python
from itertools import islice
first_million_primes = (i for i in generate_primes() if i < 1000000)
two_thousandth_prime = list(islice(first_million_primes,2001))[2000]
}}}
Most of the memory and time needed to generate this many primes will not be used until the needed element is actually accessed. Unfortunately, you cannot perform simple indexing and slicing of generators, but must use the itertools modules or "roll your own" loops. In contrast, a list comprehension is functionally equivalent, but is greedy in performing all the work:
{{{#!python
first_million_primes = [i for i in generate_primes(2000000) if i < 1000000]
two_thousandth_prime = first_million_primes[2000]
}}}
The list comprehension will immediately create a large list (with 78498 items, in the example, but transiently creating a list of primes under two million), even if most elements are never accessed. The generator comprehension is more parsimonious.

== Objects ==
Python supports most object oriented programming techniques. It allows polymorphism, not only within a class hierarchy but also by duck typing. Any object can be used for any type, and it will work so long as it has the proper methods and attributes. And everything in Python is an object, including classes, functions, numbers and modules. Python also has support for metaclasses, an advanced tool for enhancing classes' functionality. Naturally, inheritance, including multiple inheritance, is supported. It has limited support for private variables using name mangling. See the "Classes" section of the tutorial for details. Many Python users don't feel the need for private variables, though. The slogan "We're all consenting adults here" is used to describe this attitude. Some consider information hiding to be unpythonic, in that it suggests that the class in question contains unaesthetic or ill-planned internals.

From the tutorial: As is true for modules, classes in Python do not put an absolute barrier between definition and user, but rather rely on the politeness of the user not to "break into the definition."

OOP doctrines such as the use of accessor methods to read data members are not enforced in Python. Just as Python offers functional-programming constructs but does not attempt to demand referential transparency, it offers (and extensively uses!) its object system but does not demand OOP behavior. Moreover, it is always possible to redefine the class using properties so that when a certain variable is set or retrieved in calling code, it really invokes a function call, so that spam.eggs = toast might really invoke spam.set_eggs(toast). This nullifies the practical advantage of accessor functions, and it remains OOP because the property 'x' becomes a legitimate part of the object's interface: it need not reflect an implementation detail.

In version 2.2 of Python, "new-style" classes were introduced. With new-style classes, objects and types were unified, allowing the subclassing of types. Even entirely new types can be defined, complete with custom behavior for infix operators. This allows for many radical things to be done syntactically within Python. A new method resolution order for multiple inheritance was also adopted with Python 2.3. It is also possible to run custom code while accessing or setting attributes, though the details of those techniques have evolved between Python versions.

== Exceptions ==

Python supports (and extensively uses) exception handling as a means of testing for error conditions and other "exceptional" events in a program. Indeed, it is even possible to trap the exception caused by a syntax error.

Python style calls for the use of exceptions whenever an error condition might arise. Indeed, rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.

Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, the Mailman mailing list software, written in Python, uses exceptions to jump out of deeply-nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval.

Exceptions are often, especially in threaded situations, used as an alternative to the if-block. A commonly-invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than to ask for Permission." In this first code sample, there is an explicit check for the attribute (i.e., "asks permission"):
{{{#!python
if hasattr(spam, 'eggs'):
    baz = spam.eggs
else:
    handle_error()
}}}
This second sample follows the EAFP paradigm:
{{{#!python
try:
    baz = spam.eggs
except AttributeError:
    handle_error()
}}}
These two code samples have the same effect, although there will be performance differences. When spam has the attribute eggs, the EAFP sample will run faster. When spam does not have the attribute eggs (the "exceptional" case), the EAFP sample will run significantly slower. The Python programmer usually writes for code readability first, then uses Python's code profiling tools for performance analysis to determine if further optimization is required. In most cases, the EAFP paradigm results in faster and more readable code.

== Comments and docstrings ==

Python has two ways to annotate Python code. One is by using comments to indicate what some part of the code does.
{{{#!python
def getline():
    return sys.stdin.readline() # Get one line and return it
}}}
Comments begin with the hash character ("#") and are terminated by the end of line. Python does not support comments that span more than one line. The other way is to use docstrings (documentation string), that is a string that is located alone without assignment as the first line within a module, class, method or function. Such strings can be delimited with " or ' for single line strings, or may span multiple lines if delimited with either """ or ''' which is Python's notation for specifying multi-line strings. However, the style guide for the language specifies that triple double quotes (""") are preferred for both single and multi-line docstrings.

Single line docstring:
{{{#!python
def getline():
    """Get one line from stdin and return it."""
    return sys.stdin.readline()
}}}

Multi-line docstring:
{{{#!python
def getline():
    """Get one line
       from stdin
       and return it."""
    return sys.stdin.readline()
}}}

Docstrings can be as large as the programmer wants and contain line breaks (if multi-line strings are used). In contrast with comments, docstrings are themselves Python objects and are part of the interpreted code that Python runs. That means that a running program can retrieve its own docstrings and manipulate that information. But the normal usage is to give other programmers information about how to invoke the object being documented in the docstring.

There are tools available that can extract the docstrings to generate an API documentation from the code. Docstring documentation can also be accessed from the interpreter with the help() function, or from the shell with the pydoc command.

The doctest standard module uses interactions copied from Python shell sessions into docstrings, to create tests.

= Python使用技巧 =

== Python的编码处理技术 ==
= Python =

<<TableOfContents>>

 * [[Python介绍]]

== Python入门教程 ==

 * Python教程:[[Python游戏开发基础]]
 * [[https://stackify.com/learn-python-tutorials/|30个不同的Python入门网站]]
 * [[https://developers.google.com/edu/python|Google's Python Class]]
 * [[https://blog.jetbrains.com/blog/2020/03/05/jetbrains-academy-python/|Learn Python with JetBrains Academy!]]
 * [[https://docs.python.org/3/tutorial/|Python Tutorial]]
 * [[https://diveintopython3.problemsolving.io/|Dive Into Python 3]] ([[https://woodpecker.org.cn/diveintopython3/|中文版]])
 * [[https://python.swaroopch.com/|A Byte of Python]] (中文版: [[https://bop.mol.uno/|简明Python教程]])
 * [[https://en.wikibooks.org/wiki/Python_Programming|Python Programming - Wikibooks]]
 * [[https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3|Non-Programmers Tutorial For Python]]
 * [[https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/lecture-videos/|MIT 6.0001 Introduction to Computer Science and Programming in Python]]
 * [[http://openbookproject.net/thinkcs/python/english3e/|How to Think Like a Computer Scientist (Learning with Python 3)]]
 * [[http://xahlee.info/python/index.html|Python by Example]] by Xah Lee
 * [[http://www.alan-g.me.uk/l2p/|Learn to Program by Alan G]]
 * [[https://inventwithpython.com/|Invent with Python]]
 * [[http://chinesepython.org/pythonfoundry/easytut.html|Python 非編程員教學]]
 * [[http://www.norvig.com/python-lisp.html|Python for Lisp Programmers]]

已经过时的教程(基于已经淘汰的Python 2):

 * 另类的Python教程: [[attachment:我的名字叫Python.pdf]] (太古老,已过时)
 * [[http://www.wag.caltech.edu/home/rpm/python_course/|Python Short Course]] by Richard P. Muller (太古老,已过时)
 * [[https://github.com/livewires/python/releases|The LiveWires Python Course]] 已过时
 * [[http://www.pentangle.net/python/handbook/|Handbook of the Physics Computing Course]] 已过时
 * [[http://www.math.pku.edu.cn/teachers/lidf/docs/Python/python-tutorial.html|Python入门]]

== Python解释器 ==
 * CPython http://python.org/
 * Stackless Python http://www.stackless.com/
   * [[StacklessPython]]
 * Ironpython (Python for .Net) https://ironpython.net/
 * Jython (Python for Java) https://www.jython.org/
 * [[https://www.pypy.org/|PyPy]]
   * [[https://speed.pypy.org/|PyPy Speed]]
 * [[http://hylang.org|Hylang]] A dialect of Lisp that's embedded in Python

== Python开发环境 ==
 * Mac上Python环境准备: https://sourabhbajaj.com/mac-setup/Python/
 * [[http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html|One Day of IDLE Toying]] (中文版: [[http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE-chinese.htm|摆弄一天IDLE]])
 * [[http://ftp.ntua.gr/mirror/python/idle/doc/idle2.html|Using IDLE]] by Daryl Harms
 * [[https://docs.python-guide.org/dev/virtualenvs/|Pipenv & Virtual Environments]]
 * [[https://hackernoon.com/reaching-python-development-nirvana-bb5692adf30c|Why you should use pyenv + Pipenv for your Python projects]]
 * [[https://pipenv.pypa.io/en/latest/advanced/|Advanced Usage of Pipenv]]
 * [[https://python-poetry.org/|poetry]]
 * [[https://github.com/David-OConnor/pyflow|pyflow]]
 * [[https://github.com/ofek/hatch|hatch]]
 * [[https://github.com/takluyver/flit|flit]]
 *



== Python语法 ==

 * [[http://en.wikipedia.org/wiki/Python_syntax_and_semantics|Python语法]] from Wikipedia
 * [[https://docs.python-guide.org/writing/gotchas/|Python Gotchas]]
 * [[https://towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5|30 Python Best Practices, Tips, And Tricks]]
 * [[https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/|Python yield 使用浅析]]
 * [[https://python-future.org/compatible_idioms.html|Cheat Sheet: Writing Python 2-3 compatible code]]
 * [[https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html|Type hints cheat sheet (Python 3)]]
 * [[https://docs.python.org/3/reference/index.html|Python Reference Manual]]
 * [[https://realpython.com/async-io-python/|Async IO in Python: A Complete Walkthrough]]
 * [[https://snarky.ca/how-the-heck-does-async-await-work-in-python-3-5/|How the heck does async/await work in Python 3.5?]]
 * [[https://rhettinger.wordpress.com/2011/05/26/super-considered-super/|Python’s super() considered super! ]]
 * [[https://docs.python.org/3/library/asyncio-task.html|Coroutines and Tasks]]
 * [[https://www.python.org/dev/peps/pep-0492/|PEP 492 -- Coroutines with async and await syntax]]


== 代码风格 ==

 * [[https://www.python.org/doc/essays/styleguide/|Python Style Guide]]
 * https://www.python.org/dev/peps/pep-0008/
 * https://www.python.org/dev/peps/pep-0257/
 * [[https://docs.python-guide.org/writing/style/|Code Style -- The Hitchhiker's Guide to Python]]
 * [[https://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/|Open Sourcing a Python Project the Right Way]]

== 参考资料 ==

 * [[Why Python is More Productive than Java]]
 * awesome python https://github.com/vinta/awesome-python
 * [[http://www.linuxjournal.com/article/3882|Why_Python]] by Eric Raymond [[http://blog.sina.com.cn/s/blog_53982851010008b8.html|why python中文版]]

 * [[https://woodpecker.org.cn/|WoodPecker中文社区]]
 * [[https://www.reddit.com/r/programming/comments/eroi/of_snakes_and_rubies_or_why_i_chose_python_over/|Of snakes and rubies; Or why I chose Python over Ruby]]
 * [[http://www-128.ibm.com/developerworks/cn/linux/theme/special/index.html#python|ibm上的python专题]]
 * [[http://www.hetland.org/python/instant-hacking.php|Instant Hacking]] and [[http://hetland.org/python/instant-python.php|Instant Python]]
 * [[http://wiki.python.org/moin/Intro_to_programming_with_Python_and_Tkinter|Intro to programming with Python in Tkinter(Video Lesson)]]

 * [[http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html|Beginning Python for Bioinformatics]]
 * [[http://www.pasteur.fr/recherche/unites/sis/formation/python/|Python course in Bioinformatics]]
 * [[http://www.pasteur.fr/formation/infobio/python/|Introduction to Programming using Python]]
 * [[http://gvr.sourceforge.net/|The Guido van Robot]]
 * [[http://www.linuxjournal.com/article/3946|Python Programming for Beginners]]
 * [[http://www.rexx.com/~dkuhlman/python_101/python_101.html|Python 101 -- Introduction to Python]] [[http://www.rexx.com/~dkuhlman/python_201/python_201.html|Python 201 -- (Slightly) Advanced Python Topics]]
 * [[http://www.ifi.uio.no/in228/lecsplit/|Scripting for Computational Science]]
 * [[http://starship.python.net/crew/hinsen/|Python for Science]]
 * [[http://www.codeteacher.com/category.php?ID=8|Code Teacher]]
 * [[http://groups.google.com/group/comp.lang.python|Python讨论组comp.lang.python]]
 * [[http://pine.fm/LearnToProgram/|Learn to Program(ruby)]]
 * [[https://www.sitepoint.com/community/t/article-10-time-saving-tips-for-pythonists/197722|10 Time-saving Tips for Pythonists]]
 * [[https://docs.python.org/3.1/howto/advocacy.html|Python_Advocacy_HOWTO]] by A.M. Kuchling
 * Learning to Program: attachment: http://www.freenetpages.co.uk/hp/alan.gauld/
 * Learn To Program CD: [[attachment:LearnToProgramCD.zip]]
 * Tkinter Life Preserver: http://www.python.org/doc/life-preserver/
 * [[https://archive.org/details/SeanKellyRecoveryfromAddiction|Recovery from Addiction]]
 * [[https://www.zhidaow.com/post/python-modules-you-should-know|Python你必须知道的十个库]]
 * [[http://www.pythontip.com/blog/post/9771/|【外刊IT评论网】Python高效编程技巧]]
 * [[http://blog.sina.com.cn/s/blog_4e8581890102e29u.html|孩子们为什么要学Python编程?]]
 * [[https://pythonconquerstheuniverse.wordpress.com/2009/10/03/python-java-a-side-by-side-comparison/|Python & Java: A Side-by-Side Comparison]]
 * [[https://book.douban.com/subject/1241032/|Jython程序设计]]
 * [[https://lists.ubuntu.com/archives/ubuntu-devel/2020-February/040918.html|Python2 removal for Ubuntu focal]]
 * [[https://app.getpocket.com/read/2956522352|Python 2.7.18, the end of an era]]
 * [[http://python-future.org/|Easy, clean, reliable Python 2/3 compatibility]]
 * [[https://computers-are-fast.github.io/|Do you know how much your computer can do in a second?]]
 * [[https://medium.com/@jherreras/python-microlibs-5be9461ad979|Python Microlibs]]

== Python库 ==

=== 标准库 ===

 * [[http://docs.python.org/lib/lib.html|Python Library Reference]]

=== GUI Toolkit ===

 * wxpython http://www.wxpython.org/
 * [[PyGtk]]
 * [[https://kivy.org/|Kivy]] 基于OpenGL ES的移动端、桌面端GUI开发库
 * 使用PyQt编写QT图形界面程序 http://www.riverbankcomputing.co.uk/pyqt/
 * [[https://machinekoder.com/pyqt-vs-qt-for-python-pyside2-pyside/|PyQT vs PySide2]]

=== DB ===

 * [[https://elasticsearch-dsl.readthedocs.io/en/latest/|ElasticSearch DSL]]

=== 网络 ===

 * [[https://github.com/MagicStack/uvloop|uvloop]]: asyncio + libuv + Cython,再配上httptools做HTTP parser,从[[https://magic.io/blog/uvloop-blazing-fast-python-networking/|benchmark]]看起来性能非常强劲。

=== Web 开发 ===

 * [[Django]]
 * [[https://wiki.python.org/moin/WebProgramming|WebProgramming - Python Wiki]]
 * Flask: https://flask.palletsprojects.com/en/1.1.x/
 * [[https://www.youtube.com/watch?v=DWODIO6aCUE|Better Web App]]

=== Windows ===
 * pywin32 http://sourceforge.net/projects/pywin32/
 * comtypes http://starship.python.net/crew/theller/comtypes/
 * python 与 COM [[http://oreilly.com/catalog/pythonwin32/chapter/ch12.html|Advanced Python and COM]]
 * 使用_winreg模块操纵windows注册表
 * 将python程序打包成windows下可以执行的exe文件:使用[[http://www.py2exe.org/|py2exe]]模块
 * 在.net平台上使用python:[[http://www.gotdotnet.com/Workspaces/Workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742|IronPython]]

=== Mac ===
 * [[http://undefined.org/python/py2app.html|Py2app]]

=== 多媒体 ===

 * 图像获取:linux平台下使用sane模块,Windows平台下使用twain模块
   * [[http://twainmodule.sourceforge.net/|TWAIN]]
 * 图像处理[[PythonImageLibrary中文手册]]
 * 通过ffmpeg处理视频、音频 https://github.com/kkroening/ffmpeg-python
 * PyDUB:在python中直接处理音频 https://github.com/jiaaro/pydub

=== 游戏 ===
 * pygame: http://www.pygame.org/
   * [[Pygame]]
 * panda3d: http://www.panda3d.org/
 * renpy: http://www.renpy.org/wiki/renpy/Home_Page
 * pyopengl http://pyopengl.sourceforge.net/

=== 字符串 ===

 * [[https://docs.python.org/3/howto/unicode.html|Unicode Howto]]
 * http://docs.python.org/lib/module-re.html
 * http://www.amk.ca/python/howto/regex/
 * Mastering Regular Expressions 2nd Edition, By Jeffrey E. F. Friedl
 * [[https://click.palletsprojects.com/en/7.x/|Click]] 命令行参数处理

=== 数据处理 ===

 * [[https://numpy.org/|numpy]]
 * [[https://www.scipy.org/|scipy]]
 * [[https://radimrehurek.com/data_science_python/|Practical Data Science in Python]]
 * [[https://pytorch.org/|PyTorch]]
 * [[https://scikit-learn.org/stable/|Scikit-Learn]]

=== 其它 ===
 * python-ldap http://www.python-ldap.org/
   * [[PythonLdap]]
 * 读取excel:用xlrd包。把excel转成csv,使用csv库操作。
 * 加密:Python Cryptography Toolkit http://www.amk.ca/python/code/crypto
 * [[http://springpython.webfactional.com/|Spring Python]]: 为什么Python不需要像Spring这样的东西?
 * [[http://www.dabeaz.com/ply/ply.html#ply_nn2|PLY]] Python Lex-Yacc

== Python的字符编码处理 ==
行号 605: 行号 239:
== Python常用模块 ==

 * 图像获取:linux平台下使用sane模块,Windows平台下使用twain模块

 * 图像处理["PythonImageLibrary中文手册"]

 * 使用_winreg模块操纵windows注册表

 * 读取excel:用xlrd包。把excel转成csv,使用csv库操作。

 * 将python程序打包成windows下可以执行的exe文件:使用[http://www.py2exe.org/ py2exe]模块

 * 加密:Python Cryptography Toolkit http://www.amk.ca/python/code/crypto
 * 在.net平台上使用python:[http://www.gotdotnet.com/Workspaces/Workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742 IronPython]


= The end =
 * [[Python代码片段]]

Python

1. Python入门教程

已经过时的教程(基于已经淘汰的Python 2):

2. Python解释器

3. Python开发环境

4. Python语法

5. 代码风格

6. 参考资料

7. Python库

7.1. 标准库

7.2. GUI Toolkit

7.3. DB

7.4. 网络

  • uvloop: asyncio + libuv + Cython,再配上httptools做HTTP parser,从benchmark看起来性能非常强劲。

7.5. Web 开发

7.6. Windows

7.7. Mac

7.8. 多媒体

7.9. 游戏

7.10. 字符串

7.11. 数据处理

7.12. 其它

8. Python的字符编码处理

对于中文用户,特别需要关注Python的编码技术. 列举一些常用的技巧。

chr(i): 将一个0到255的整数转换为一个字符.
ord(c): 返回单个字符c的整数顺序值.普通字符返回[0,255]中的一个值,Unicode字符返回 [0,65535]中的一个值
unichr(i): 将一个0到65535的整数转换为一个Unicode字符
  • 代码中的编码设置,应该在代码最初两行内包含:

# -*- coding: UTF-8 -*-
  • 获得/设置系统的缺省编码

sys.getdefaultencoding()

sys.setdefaultencoding('utf-8')
  • 获得文件系统的文件名的编码

sys.getfilesystemencoding()
  • 获得当前终端的输入、输出编码

      sys.stdout.encoding

      sys.stdin.encoding
  • 编码转换(先转换为unicode,再转换为具体的编码),有两种方法:

      unicode('abc', 'mbcs').encode('utf-8')

      'abc'.decode('mbcs').encode('utf-8')

Python (2020-06-05 17:12:03由czk编辑)

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