Python Docs 笔记

来源:互联网 发布:php 自动实例化类 编辑:程序博客网 时间:2024/06/07 12:03

Python enables programs to be written compactly and readably. Programs written in Python are typically much shorter than equivalent C, C++, or Java programs, for several reasons:

  • the high-level data types allow you to express complex operations in a single statement;
  • statement grouping is done by indentation instead of beginning and ending brackets;
  • no variable or argument declarations are necessary.

else statements

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

>>> for n in range(2, 10):...     for x in range(2, n):...         if n % x == 0:...             print n, 'equals', x, '*', n/x...             break...     else:...         # loop fell through without finding a factor...         print n, 'is a prime number'...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.)

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.


*name & **name

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.) For example, if we define a function like this:

def cheeseshop(kind, *arguments, **keywords):    print "-- Do you have any", kind, "?"    print "-- I'm sorry, we're all out of", kind    for arg in arguments:        print arg    print "-" * 40    keys = sorted(keywords.keys())    for kw in keys:        print kw, ":", keywords[kw]

It could be called like this:

cheeseshop("Limburger", "It's very runny, sir.",           "It's really very, VERY runny, sir.",           shopkeeper='Michael Palin',           client="John Cleese",           sketch="Cheese Shop Sketch")

and of course it would print:

-- Do you have any Limburger ?-- I'm sorry, we're all out of LimburgerIt's very runny, sir.It's really very, VERY runny, sir.----------------------------------------client : John Cleeseshopkeeper : Michael Palinsketch : Cheese Shop Sketch

Note that the list of keyword argument names is created by sorting the result of the keywords dictionary’s keys() method before printing its contents; if this is not done, the order in which the arguments are printed is undefined.

lamda expression ????

python tutorial: 4.7.5

def make_incrementor(n):        return lamda x: x + n    f = make_incrementor(42) <=> f = lamda x: x+ 42f(0) <=> lamda 0: 0 + 42f(1) <=> lamda 1: 1 + 42

??????
The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:

> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]> pairs.sort(key=lambda pair: pair[1])> pairs[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

coding style

For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:

  • Use 4-space indentation, and no tabs.

4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.

  • Wrap lines so that they don’t exceed 79 characters.

This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.

  • Use blank lines to separate functions and classes, and larger blocks of code inside functions.

  • When possible, put comments on a line of their own.

  • Use docstrings.

  • Use spaces around operators and after commas, but not directly inside bracketing constructs:a = f(1, 2) + g(3, 4).

  • Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscoresfor functions and methods. Always use self as the name for the first method argument (see !A First Look at Classes for more on classes and methods).

  • Don’t use fancy encodings if your code is meant to be used in international environments. Plain ASCII works best in any case.

looping techniques

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>> questions = [‘name’, ‘quest’, ‘favorite color’]
>>> answers = [‘lancelot’, ‘the holy grail’, ‘blue’]
>>> for q, a in zip(questions, answers):
… print ‘What is your {0}? It is {1}.’.format(q, a)

What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

xrange()

  • class xrange(object)

xrange(stop) -> xrange object
xrange(start, stop[, step]) -> xrange object

Like range(), but instead of returning a list, returns an object that
generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient.