python - 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.
解决方案
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.
推荐阅读
- arrays - 仅当条件满足时才创建实例
- python - 运行 py.test 时导入错误
- swift - 如何在 Swift 4 中为 NSTabViewController 创建自定义导航栏
- c++ - 由于动态链接库中的虚函数导致编译错误
- scala - 使用流响应有时会导致“对等连接重置”错误
- python - Django 填充器不起作用。ImportError:无法导入名称混合
- python - 重新运行单元格时,Jupiter notebook 中的 BackTrader 图表消失
- ios - 如何在颤动中获取捆绑包ID
- mysql - 如何只带一个字段重复但另一个字段在一个范围内变化的行?
- asp.net - log4net 在类库中不起作用