2013-07-02 22 views
-1

我动态创建一个功能是这样的:如何创建一个动态获取指定数量参数的Python函数?

def create_function(value): 
    def _function(): 
     print value 
return _function 

f1 = create_func(1) 
f1() 

的正常工作,并打印“1”。

但我的问题稍有不同,比如说有一个名为no_of_arguments的变量,其中包含正在返回的函数(_function())所使用的参数数量。

def create_function(): 
    no_of_arguments = int(raw_input()) #provided by user 
    def _function(a,b,c,....): 

“这个函数必须接受一定数目的参数,在可变no_of_arguments指定的”由前一与

 #do something here 
return _function 

f1 = create_func() 
f1(a,b,c......) 
+2

也许你应该在...之后解释你真的*真的* –

+1

我不明白你真正想要什么,但是在Python中有任意参数的函数有'* args'和'** kwargs'关键字。可能他们会很有帮助。 –

回答

0

的函数可以被定义为服用的参数中的任何(最小)数一个*,这将导致名称被绑定到包含适当参数的元组。

def foo(a, b, *c): 
    print a, b, c 

foo(1, 2, 3, 4, 5) 

您将需要限制/检查自己通过这种方式通过的值的数量。

1

在函数参数中使用*以使其接受任意数量的位置参数。

def func(*args): 
    if len(args) == 1: 
     print args[0] 
    else: 
     print args 
...   
>>> func(1) 
1 
>>> func(1,2) 
(1, 2) 
>>> func(1,2,3,4) 
(1, 2, 3, 4) 
0

你可以使用*args

def create_function(): 
    no_of_arguments = int(raw_input()) #provided by user 
    def _function(*args): 
     if len(args) == no_of_arguments: 
      dostuff() 
     else: 
      print "{} arguments were not given!".format(no_of_arguments) 
    return _function 

运行它作为一个例子:

>>> f1 = create_function() 
4 # The input 
>>> f1('hi','hello','hai','cabbage') 
>>> f1('hey') 
4 arguments were not given! 
0

据我了解,你需要不同数量的参数传递给函数 你可以使用*来传递不同数量的参数:

def create_function(): 
    no_of_arguments = (argList) #tuple of arguments 
    def _function(*argList): 
相关问题