Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何动态创建接受指定数量参数的Python函数?_Python_Python 2.7_Runtime - Fatal编程技术网

如何动态创建接受指定数量参数的Python函数?

如何动态创建接受指定数量参数的Python函数?,python,python-2.7,runtime,Python,Python 2.7,Runtime,我通过以下方式动态创建函数: def create_function(value): def _function(): print value return _function f1 = create_func(1) f1() 它可以很好地打印“1” 但我的问题略有不同,比如说有一个名为no_of_arguments的变量,它包含返回的函数(_function())接受的参数数 '此函数必须接受在变量no_of_arguments中指定的一定数量的参数'

我通过以下方式动态创建函数:

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

f1 = create_func(1)
f1()
它可以很好地打印“1”

但我的问题略有不同,比如说有一个名为no_of_arguments的变量,它包含返回的函数(_function())接受的参数数

'此函数必须接受在变量no_of_arguments中指定的一定数量的参数'

        #do something here
return _function

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

函数可以定义为通过在一个参数前面加上
*
来获取任意(最小)个参数,这将导致名称绑定到包含适当参数的元组

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

foo(1, 2, 3, 4, 5)
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)

您需要自己限制/检查以这种方式传递的值的数量。

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

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

foo(1, 2, 3, 4, 5)
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)
您可以使用:

以运行它为例:

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

据我所知,您需要向函数传递不同数量的参数 您可以使用*传递不同数量的参数,如下所示:

def create_function():
    no_of_arguments = (argList) #tuple of arguments
    def _function(*argList): 

也许你应该解释一下你真正想要的是什么……我不明白你真正想要的是什么,但是对于Python中带有任意参数的函数,有
*args
**kwargs
关键字。也许他们会有所帮助。