如何在Python中传递接收参数作为另一个函数的参数的方法

Luc*_*cas 2 python parameter-passing

我知道这是有效的:

def printValue():
    print 'This is the printValue() method'

def callPrintValue(methodName):
    methodName()
    print 'This is the callPrintValue() method'
Run Code Online (Sandbox Code Playgroud)

但有没有办法传递一个接收参数作为另一个函数的参数的方法?

这样做是不可能的:

def printValue(value):
    print 'This is the printValue() method. The value is %s'%(value)

def callPrintValue(methodName):
    methodName()
    print 'This is the callPrintValue() method'
Run Code Online (Sandbox Code Playgroud)

这是我得到的堆栈跟踪:

This is the printValue() method. The value is dsdsd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in callPrintValue
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)

sen*_*rle 8

有些人觉得lambda很难看,但在这种情况下它是一个很有用的工具.callPrintValue()您可以使用lambda快速定义绑定参数的新函数,而不是修改签名printValue().您是否真的想要这样做取决于许多因素,并且可能更*args喜欢添加其他人建议的参数.不过,这是一个值得考虑的选择.以下工作无需修改您当前的代码:

>>> callPrintValue(lambda: printValue('"Hello, I am a value"'))
This is the printValue() method. The value is "Hello, I am a value"
This is the callPrintValue() method
Run Code Online (Sandbox Code Playgroud)


Str*_*des 6

def printValue(value):
    print 'This is the printValue() method. The value is %s'%(value)

def callPrintValue(methodName, *args):
    methodName(*args)
    print 'This is the callPrintValue() method'
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

callPrintValue(printValue, "Value to pass to printValue")
Run Code Online (Sandbox Code Playgroud)

这允许您传入任意数量的参数,并将所有参数传递给您调用的函数 callPrintValue