【问题标题】:Confused with function-object usage in Python [closed]对 Python 中的函数对象用法感到困惑 [关闭]
【发布时间】:2013-03-20 12:15:46
【问题描述】:

我目前正在使用“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 为 垃圾邮件 垃圾邮件 我不知道怎么做,我想对这个概念进行更深入的解释

【问题讨论】:

  • 您的问题是什么?你有什么不明白的?

标签: python function object parameters


【解决方案1】:

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

在上面的示例会话中,我使用了print_spam 函数对象,将其分配给another_name,然后通过其他变量调用它。

您从 Think Python 中引用的代码所做的只是将 print_spam 作为参数传递给函数 do_twice,该函数调用它的参数 f 两次。

【讨论】:

  • 仍然不清楚他们为什么以及如何使用那个 f()
  • f 是函数do_twice() 的参数。通过给该函数一个对另一个函数的引用,f 成为对该另一个函数的引用。添加() 然后调用引用的函数。
  • 是的,我终于明白了。 print_spam = f 和内部 do_twice f() = print_spam() 感谢 Martijn Pieters
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多