2 回答

TA贡献1848条经验 获得超2个赞
我认为这可以满足您的所有要求,充分利用Python 的函数对象数据模型:
def my_func (b1, b2, b3, a1, a2, a3):
par_names = my_func.__code__.co_varnames[:6] # A tuple of strings of all param names
# It's ok to hard-code 6.
local_ns = locals()
par_vals = [local_ns[x] for x in par_names] # A list of all param values
another_func(par_vals[0], par_vals[3])
another_func(*par_vals[0:2]) # Unpacking first 2 params
def another_func(param1, param2):
print ("Inside another_func, (param1, param2) are:", param1, ",", param2)
my_func(10, 20, 30, 40, 50, 60)
输出:
Inside another_func, (param1, param2) are: 10 , 40
Inside another_func, (param1, param2) are: 10 , 20
笔记:
对于参数名称
b1
,无需遵循,b2
,等命名约定。适用于任意数量的参数(不仅仅是示例中的 32 个)。
即使某些参数是 kwargs 也能工作。
如文档所述,
__code__.co_varnames
将包含参数名称,后跟局部变量名称。因此,我们对前 6 个元素进行索引,以仅获取参数名称。
添加回答
举报