如何通过接收参数,在Python

问题描述:

一个另一个函数的参数的方法,我知道这是有效的:如何通过接收参数,在Python

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

def callPrintValue(methodName): 
    methodName() 
    print 'This is the callPrintValue() method' 

但有一种方式来传递接收参数作为另一个函数的参数的方法?

这样做是不可能的:

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

def callPrintValue(methodName): 
    methodName() 
    print 'This is the callPrintValue() method' 

这是堆栈跟踪我得到:

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 

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' 

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

callPrintValue(printValue, "Value to pass to printValue") 

这允许你传入任意数量的参数,并且al其中L为传递给你callPrintValue

调用函数我想你可以做到这一点


def callPrintValue(methodName, *args): 
    methodName(*args) 
    print 'This is the callPrintValue() method' 

拨打电话


callPrintValue(printValue, "abc") 

您想使用的元组拆包:

def print_value(*values): 
    print values 

def call_print_value(func,args=None): 
    func(*args) 

call_print_value(print_value,args=('this','works')) #prints ('this', 'works') 

从API的角度来看,我倾向于保留传递的参数为单独的关键字。 (然后它更清楚地指出哪些参数正在被print_value使用,哪些正在被call_print_value使用)。还要注意,在python中,函数(和方法)的名字通常是name_with_underscores。 CamelCase通常用于类名称。

有些人发现lambda丑陋,但它是这种情况下的一个有用的工具。您可以使用lambda快速定义一个将参数绑定到printValue()的新函数,而不是修改callPrintValue()的签名。您是否真的想要这样做取决于很多因素,并且可能会像其他人所建议的那样添加*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 
+1

我同意'lambda'可所谓这里(+1)。事实上,这就是GUI编程中的常用方法(例如'tkinter'),因为您没有办法修改执行回调的函数。 – mgilson 2012-07-16 13:01:58

作为后续行动已经提供的答案,你可能要检查出计算器的下列问题以便更好地理解*参数的个数和/或** kwargs和lambda在python中。

  1. What does *args and **kwargs mean?
  2. What does ** (double star) and * (star) do for python parameters?
  3. Python Lambda - why?