Python动态函数参数

2024-05-26 11:10:03 发布

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

调用下面的函数时,我可以提供将要使用的值,而不是函数中的默认参数(请参见下文)

cerebro.addstrategy(GoldenCross, fast=10, slow=25)

这对于少量已知参数非常有效,但我将转向更复杂的系统。基本上,我需要通过一个fast_1,fast_2,fast_3,等等。。。。这些参数的总量将发生变化(始终在100左右,但可能会有所变化)。是否有一个我可以编写的语句将动态地向我的函数调用添加X个参数

我尝试在函数调用中使用for语句,但收到语法错误


Tags: 函数for参数系统动态语句fastslow
3条回答

使用*怎么样? def addstrategy(GoldenCross, *fast, slow = 25):就是一个例子

>>> def foo(a, *b, c = 36):
        print(a, b, c)
>>> foo(1, 2, 3, 4, 5)
1 (2, 3, 4, 5) 36

但是,在这种情况下,您需要初始化fast

我从两个方面理解了你的问题:

  1. 如果要调用传递不同参数(可选)的函数,可以按如下方式完成:
def add(first, second=0, third=3):
    return (first+second+third)
    
number_list = list(range(1, 200))  # Generates a list of numbers
result = []  # Here will be stored the results


for number in number_list:
    # For every number inside number_list the function add will
    # be called, sending the corresponding number from the list.
    returned_result = add(1,second=number)
    result.insert(int(len(result)), returned_result)

print(result) # Can check the result printing it
  1. 您希望函数处理任意数量的可选参数,因为您不知道如何确定它们的数量,您可以发送一个列表或参数,如下所示:
def add(first,*argv):
    for number in argv:
        first += number
    return first

number_list = (list(range(1, 200)))  # Generates a list of numbers
result = add(1,*number_list)  # Store the result

print(result) # Can check the result printing it

Here您可以找到有关*args的更多信息

两种方法:要么对参数使用*变量数,要么将参数视为iterable

def fun1(positional, optional="value", *args):
  print(args) # args here is a tuple, since by default variable number of args using * will make that parameter a tuple.

def fun2(positional, args, optional="value"):
  print(args) # args here will be dependant on the argument you passed.

fun1("some_value", "value", 1, 2, 3, 4, 5) # args = (1, 2, 3, 4, 5)
fun2("some_value", [1, 2, 3, 4, 5]) # args = [1, 2, 3, 4, 5]

相关问题 更多 >