在其他函数python中传递函数作为参数

mia*_*ech 2 python function

我有这些函数,并且我遇到错误,使用do_twice函数,但是我在调​​试它时遇到了问题

#!/usr/bin/python
#functins exercise 3.4

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

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

def print_twice(str):
    print str + 'one' 
    print str + 'two'


str = 'spam'
do_four(print_twice(str))
Run Code Online (Sandbox Code Playgroud)

调试器错误

:!python 'workspace/python/functions3.4.py'
spamone
spamtwo
Traceback (most recent call last):
  File "workspace/python/functions3.4.py", line 18, in <module>
    do_four(print_twice(str))
  File "workspace/python/functions3.4.py", line 9, in do_four
    do_twice(f)
  File "workspace/python/functions3.4.py", line 5, in do_twice
    f()
TypeError: 'NoneType' object is not callable

shell returned 1
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 11

问题是,表达print_twice(str)是通过调用评估print_twicestr和得到,你回来了,*并且结果是你传递什么样的参数结果do_four.

你需要传递的do_four是一个函数,当被调用时,调用print_twice(str).

您可以手动构建此类功能:

def print_twice_str():
    print_twice(str)
do_four(print_twice_str)
Run Code Online (Sandbox Code Playgroud)

或者你可以内联做同样的事情:

do_four(lambda: print_twice(str))
Run Code Online (Sandbox Code Playgroud)

或者您可以使用高阶函数partial为您执行此操作:

from functools import partial
do_four(partial(print_twice, str))
Run Code Online (Sandbox Code Playgroud)

该文档partial有一个非常好的解释:

所述partial()用于局部功能应用其中"冻结"的函数的参数和/或产生具有简化签名的新对象的关键字一些部分.例如,partial()可以用于创建一个callable,其行为类似于base参数默认为2 的int()函数:[snip]basetwo = partial(int, base=2)


*如果您正在考虑"但我没有返回任何内容,那么它None来自哪里?":每个函数总是返回Python中的值.如果你不告诉它要返回什么,它会返回None.