与Python中的函数对象用法混淆

与Python中的函数对象用法混淆,python,function,object,parameters,Python,Function,Object,Parameters,我目前正在使用“Think python”学习python,其中我学习了下面的某段代码,作为一名初学者,我不理解它是如何工作的,请向我解释下面的代码以及它背后的各种概念 练习:函数对象是可以指定给变量或作为参数传递的值。对于 例如,do_tweep是一个函数,它将函数对象作为参数并调用它两次: def do_twice(f): f() f() # Here’s an example that uses do_twice to call a function named prin

我目前正在使用“Think python”学习python,其中我学习了下面的某段代码,作为一名初学者,我不理解它是如何工作的,请向我解释下面的代码以及它背后的各种概念

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

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作为 垃圾邮件 垃圾邮件
我不知道怎么做,我想对这个概念进行更深入的解释,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
>>def print_spam():
...     打印“垃圾邮件”
... 
>>>打印垃圾邮件
>>>类型(打印垃圾邮件)
>>>另一个\u名称=打印\u垃圾邮件
>>>另一个名字
>>>另一个名称是print\u spam
真的
>>>另一个名字()
垃圾邮件
在上面的示例会话中,我使用
print\u spam
函数对象,将其分配给
另一个\u名称
,然后通过另一个变量调用它


您从Think Python中引用的所有代码都是将
print\u spam
作为参数传递给函数
do\u tweep
,该函数两次调用它的参数
f

您的问题是什么?你不明白什么?仍然不清楚他们为什么以及如何使用f()
f
是函数的参数
dou\u tweep()
。通过将该函数引用到另一个函数,
f
将成为对该另一个函数的引用。添加
()
然后调用引用的函数。是的,我终于得到了它。print_spam=f和inside do_两次f()=print_spam(),感谢Martijn Pieters