4.5 Doing More with Functions 关于函数的更多使用
This section discusses more advanced features, which you may prefer to skip on the first time through this chapter.
Functions as Arguments 函数作为参数
So far the arguments we have passed into functions have been simple objects like strings, or structured objects like lists. Python also lets us pass a function as an argument to another function. Now we can abstract out the operation, and apply a different operation on the same data. As the following examples show, we can pass the built-in function len() or a user-defined function last_letter() as arguments to another function:
|
The objects len and last_letter can be passed around like lists and dictionaries. Notice that parentheses are only used after a function name if we are invoking the function; when we are simply treating the function as an object these are omitted(注意如果我们调用函数,参数仅用在函数名之后;当我们简单地把函数作为对象时,参数忽略).
Python provides us with one more way to define functions as arguments to other functions, so-called lambda expressions. Supposing there was no need to use the above last_letter() function in multiple places, and thus no need to give it a name. We can equivalently write the following:
|
Our next example illustrates passing a function to the sorted() function. When we call the latter with a single argument (the list to be sorted), it uses the built-in comparison function cmp(). However, we can supply our own sort function, e.g. to sort by decreasing length.
|
Accumulative Functions 累加函数
These functions start by initializing some storage, and iterate over input to build it up, before returning some final object (a large structure or aggregated result). A standard way to do this is to initialize an empty list, accumulate the material, then return the list, as shown in function search1() in Example 4.6.
|
||
Example 4.6 (code_search_examples.py): Accumulating Output into a List
|
The function search2() is a generator. The first time this function is called, it gets as far as the yield statement and pauses. The calling program gets the first word and does any necessary processing. Once the calling program is ready for another word, execution of the function is continued from where it stopped, until the next time it encounters a yield statement. This approach is typically more efficient, as the function only generates the data as it is required by the calling program, and does not need to allocate additional memory to store the output (cf. our discussion of generator expressions above).
Here's a more sophisticated example of a generator which produces all permutations(排列) of a list of words. In order to force the permutations() function to generate all its output, we wrap it with a call to list() .
Note
The permutations function uses a technique called recursion, discussed below in Section 4.7. The ability to generate permutations of a set of words is useful for creating data to test a grammar (Chapter 8).
Higher-Order Functions 高级函数
Python provides some higher-order functions that are standard features of functional programming languages such as Haskell. We illustrate them here, alongside the equivalent expression using list comprehensions.
Let's start by defining a function is_content_word() which checks whether a word is from the open class of content words(实词的开放类). We use this function as the first parameter offilter(), which applies the function to each item in the sequence contained in its second parameter, and only retains the items for which the function returns True.
|
Another higher-order function is map(), which applies a function to every item in a sequence(对序列中的每一项使用函数). It is a general version of the extract_property() function we saw inSection 4.5. Here is a simple way to find the average length of a sentence in the news section of the Brown Corpus, followed by an equivalent version with list comprehension: calculation:
|
In the above examples we specified a user-defined function is_content_word() and a built-in function len(). We can also provide a lambda expression. Here's a pair of equivalent examples which count the number of vowels in each word.
|
The solutions based on list comprehensions are usually more readable than the solutions based on higher-order functions, and we have favored the former approach throughout this book(使用列表解析的方法可读性更好).
Named Arguments 参数命名
When there are a lot of parameters it is easy to get confused about the correct order. Instead we can refer to parameters by name, and even assign them a default value just in case one was not provided by the calling program. Now the parameters can be specified in any order, and can be omitted.
|
These are called keyword arguments(关键字参数). If we mix these two kinds of parameters, then we must ensure that the unnamed parameters precede the named ones. It has to be this way, since unnamed parameters are defined by position. We can define a function that takes an arbitrary number of unnamed and named parameters, and access them via an in-place list of arguments *args and an "in-place dictionary" of keyword arguments **kwargs. (Dictionaries will be presented in Section 5.3.)
|
When *args appears as a function parameter, it actually corresponds to all the unnamed parameters of the function. Here's another illustration of this aspect of Python syntax, for the zip() function which operates on a variable number of arguments. We'll use the variable name *song to demonstrate that there's nothing special about the name *args.
|
It should be clear from the above example that typing *song is just a convenient shorthand, and equivalent to typing out song[0], song[1], song[2].
Here's another example of the use of keyword arguments in a function definition, along with three equivalent ways to call the function:
|
A side-effect of having named arguments is that they permit optionality. Thus we can leave out any arguments where we are happy with the default value:freq_words('ch01.rst', min=4), freq_words('ch01.rst', 4). Another common use of optional arguments is to permit a flag(标记). Here's a revised version of the same function that reports its progress if a verbose flag is set:
|
Caution!
Take care not to use a mutable object as the default value of a parameter.(注意不要使用可变对象作为参数的缺省值) A series of calls to the function will use the same object, sometimes with bizarre results as we will see in the discussion of debugging below.