设置关键字参数的默认值时可以引用位置参数吗?

问题描述 投票:0回答:1

我正在编写一个辅助python函数,该函数将两个列表作为参数并对其进行迭代。通常,第二个列表必须是零数组,且长度与第一个相同。我想将第二个列表设置为关键字参数,并为其指定此默认值。

def iterate(list_a, list_b = np.zeros((len(list_a),), dtype=int)):
    for a, b in zip(list_a, list_b):
        # do something with a and b

但是,我得到一个未定义list_a的错误,表明在定义函数时,我无法在方括号中执行自引用计算。一个明显的解决方案是为list_b选择一个特殊的默认值,并且如果在调用函数时保持不变,则使用if语句将其更改为零列表:

def iterate(list_a, list_b = 'zeros'):

    if list_b == 'zeros':
        list_b = np.zeros((len(list_a),), dtype=int)

    for a, b in zip(list_a, list_b):
        # do something with a and b

这个解决方案在我看来似乎不是很Python,我想知道是否有更好的做法。

我将其保留为一般性目的,但是如果需要,我可以提供更多有关我的功能的细节。

python refactoring
1个回答
0
投票

不,这不能完成,但是您已经以通常的方式解决了这个问题。通常,在这种情况下,人们会将默认值设置为None并执行相同的操作(只是因为这种方式对于键入和输入变得不那么麻烦了-该函数可以接受数组或不接受任何内容,而不接受数组或字符串。)] >

就可用性而言,您可以告诉用户在doc脚本中有效的默认值是什么。

def iterate(list_a, list_b=None):
    'list_b defaults to zero array of size a'
    if not list_b:
        list_b = np.zeros((len(list_a),), dtype=int)

    for a, b in zip(list_a, list_b):
        # do something with a and b

之所以不可能,是因为当您在同一行中调用list_a变量时还没有创建它,因为python解释器是逐行进行的。

© www.soinside.com 2019 - 2024. All rights reserved.