简体   繁体   中英

Python dynamic function parameters

When calling the function below, I can provide values that will be used instead of the default parameters in the function (see below).

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

This works great for a small number of known parameters, but I am moving up to more complex systems. Essentially, I need to pass a fast_1, fast_2, fast_3, etc.... The total amount of these parameters will change (always around 100, but it can vary). Is there a statement that I can write that will dynamically add X amount of parameters to my function call?

I have tried using a for statement in the function call, but I received a syntax error.

how about using * ? def addstrategy(GoldenCross, *fast, slow = 25): can be an example.

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

You need to initialize fast in this case, however.

I understood your question of two ways:

  1. You want to call your function passing to it different parameters (that are optional), you can accomplish it like this:
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. You want your function handles any number of optional parameters, as you don't know any way to determine how many they are, you can send a list or parameters, like this:
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 you can find more information about *args

Two ways: Either use a variable number of arguments using * on the parameter or treat the parameter as an 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM