首页 > 解决方案 > Python动态函数参数

问题描述

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

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

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

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

标签: pythonbacktrader

解决方案


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

  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

在这里您可以找到有关 *args 的更多信息


推荐阅读