Python:如何将多参数作为单个变量传入函数?含调用场景
问题解决方案
一、设置outer_function的默认值,实现调用outer_function()输出三个'nothing'
当前outer_function直接将parameter_set作为单个参数传递给inner_function,会覆盖parameter1的默认值,无法触发三个参数的默认行为。需要先修改outer_function的调用逻辑,使用参数解包语法,再设置对应默认值:
方案1:基于位置参数元组
修改outer_function代码:
def outer_function(parameter_set=()): inner_function(*parameter_set)
将默认值设为空元组(),调用outer_function()时,inner_function(*())等价于直接调用inner_function(),三个参数均使用默认值'nothing'。
方案2:基于关键字参数字典
修改outer_function代码:
def outer_function(parameter_set={}): inner_function(**parameter_set)
将默认值设为空字典{},调用outer_function()时,inner_function(**{})同样等价于直接调用inner_function(),输出三个'nothing'。
二、传入参数实现输出'nothing'、'wamo'、'thunk'
根据上述两种方案,对应两种传参方式:
若使用方案1(位置参数元组)
需传入包含三个元素的元组,第一个元素为'nothing'(匹配parameter1的默认值),后两个为目标值:
outer_function(('nothing', 'wamo', 'thunk'))
若使用方案2(关键字参数字典)
只需传入包含parameter2和parameter3的字典,parameter1自动使用默认值:
outer_function({'parameter2': 'wamo', 'parameter3': 'thunk'})
这种方式无需重复传递默认值,逻辑更清晰。
内容的提问来源于stack exchange,提问作者Michael Bunalski
相关产品推荐
相关产品推荐

