Python 3.x中如何显式指定可变位置参数other调用函数?
解决Python中显式指定可变位置参数名称的问题
原函数中的*other是可变位置参数收集器,它本身并非可通过关键字传递的参数,因此直接调用时无法用other=xxx的形式传参。以下是两种可行的解决思路:
一、修改函数定义(推荐)
方式1:改为仅限关键字参数
用*作为位置参数与关键字参数的分隔符,强制other通过关键字传递,调用意图更清晰:
def my_function(a, b, *, other=()): print(a) print(b) for item in other: print(item) # 调用示例 my_function(a=1, b=2, other=[4,5,6])
方式2:兼容新旧调用方式
如果需要同时支持原位置参数调用和新的关键字调用,可以保留位置参数收集器并新增other关键字参数:
def my_function(a, b, *args, other=None): # 优先使用显式传入的other,否则用位置参数收集的内容 target_other = other if other is not None else args print(a) print(b) for item in target_other: print(item) # 两种调用都生效 my_function(1, 2, 4, 5, 6) # 原位置参数方式 my_function(a=1, b=2, other=(4,5,6)) # 显式指定other的方式
二、不修改函数定义的折中方案
若无法修改原函数,可通过变量命名加注释的方式提升可读性:
other_items = [4,5,6] my_function(a=1, b=2, *other_items) # 注:*other_items 对应函数中的other参数
内容的提问来源于stack exchange,提问作者Josh.h
相关产品推荐
相关产品推荐

