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

2024-05-20 01:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这些函数,我得到了错误,有两个do_函数,但是我调试它有问题

#!/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))

调试器错误

:!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

Tags: 函数inpybinusrdef错误line
3条回答

问题是表达式print_twice(str)是通过用str调用print_twice来计算的,并得到返回的结果,*而这个结果就是作为参数传递给do_four的结果。

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

您可以手动构建这样的函数:

def print_twice_str():
    print_twice(str)
do_four(print_twice_str)

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

do_four(lambda: print_twice(str))

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

from functools import partial
do_four(partial(print_twice, str))

partial的文档有一个很好的解释:

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two: [snip] basetwo = partial(int, base=2)


*如果你想的是“但是我没有返回任何内容,那么None是从哪里来的?”:每个函数总是返回Python中的值。如果不告诉它返回什么,它将返回None

现在print_twice正在返回None,这就是作为参数传递给do_four的结果。换句话说,传递的是函数调用的结果,而不是函数调用本身。

相反,您希望将该函数调用包装为lamda函数,如下所示:

do_four(lambda: print_twice(str))

这将把实际的函数调用作为参数传递,而不是调用函数并传递其结果。

在传递表达式之前,行do_four(print_twice(str))首先计算括号中的表达式。由于print_tweed不返回任何内容,因此假定为None,并通过。

相关问题 更多 >