首页 > 解决方案 > Optional arguments in nested functions in Python

问题描述

Is it possible for one function to take as an argument the name of one of the optional arguments of a second function then call the second function with the optional argument set to the value of some variable in the first function?

Code (that obviously doesn't work)

def foo(a=1,b=2,c=3):
    d = a + b + c
    return d

def bar(variable):
    z = get_user_input()
    e = foo(variable = z)
    return e

print(bar(a))

The desired result is for bar to call foo(a=z) and print whatever z+2+3 is. Of course Python doesn't know what (a) is here. My guess is that I can somehow reference the list of arguments of foo() , but I am stumped as to how you might do that.

标签: pythonfunction

解决方案


Maybe try the code snippet below

def foo(a=1,b=2,c=3):
    d = a + b + c
    return d

def bar(variable: str):
    z = int(input())
    e = foo(**{variable: z})
    return e

# variable name should be defined as string
print(bar("a"))

The ** parses all arbitrary arguments on dict, in this case is a. Be careful tho, as if passing wrong variable name (differ from a, b or c) will result raising error.


推荐阅读