-1

我目前正在使用“Think Python”学习python,其中我通过了如下的一段代码,并且作为一个初学者程序员,我不明白它是如何工作的,请向我解释下面的代码以及它背后的各种概念。

练习:函数对象是可以分配给变量或作为参数传递的值。例如,do_twice 是一个将函数对象作为参数并调用它两次的函数:

def do_twice(f):
    f()
    f()

# Here’s an example that uses do_twice to call a function named print_spam twice.

def print_spam():
    print 'spam'

do_twice(print_spam)

此代码将 o/p 作为垃圾邮件我不知道如何,我想更深入地解释这个概念

4

1 回答 1

3

Python 函数是一流的对象。就像其他对象一样,它们可以分配给变量并传递。

>>> def print_spam():
...     print 'spam'
... 
>>> print_spam
<function print_spam at 0x105722ed8>
>>> type(print_spam)
<type 'function'>
>>> another_name = print_spam
>>> another_name
<function print_spam at 0x105722ed8>
>>> another_name is print_spam
True
>>> another_name()
spam

In the above example session I play around with the print_spam function object, assigning it to another_name, then invoking it via that other variable.

All that the code you quoted from Think Python does is pass print_spam as a parameter to the function do_twice, which calls it's parameter f twice.

于 2013-03-29T18:32:38.690 回答