简体   繁体   中英

Use a function's returned values as parameters for another function

Is it possible to use the returned values of one function as parameters for another, for example:

def first_func():
    string1 = 'test1'
    string2 = 'test2'

    return string1, string2

def second_func(val1, val2):
    print(val1, val2)

second_func(first_func())

Attempting to do this raises Parameter 'val2' unfilled

These are examples, *args is not appropriate to use in the actual code's case.

Don't return two single strings. Instead use two functions. Each for one value:

def first_func():
    string1 = 'test1'

    return string1

def second_func():
    string2 = 'test2'

    return string2

def third_func(val1, val2):
    print(val1, val2)

third_func(first_func(), second_func())

Alternatively, create a stringarray in the first function and expect it from the function wich prints the content:

def first_func():
    string1 = 'test1'
    string2 = 'test2'

    array = [string1, string2]

    return array

def third_func(array):
    for item in array:
      print(item)

third_func(first_func())

Results of first_func are returned as a tuple, which is a single object, containing several values. second_func accepts two inputs, and in your case, should accept a single input containing several values. For your case:

def first_func():
    string1 = 'test1'
    string2 = 'test2'

    return string1, string2

def second_func(vals):
    for value in vals:
        print(value)

second_func(first_func())

This way also accepts an arbitrary number of inputs for the second function.

Of course you can also play with unpacking in the second function:

def second_func(**vals):
    print(vals)

second_func(input1 = first_func()[0], input2 = first_func()[1]) # etc. Could be done in a loop

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