Python中的默认空列表与* args

时间:2015-08-20 16:26:51

标签: python

我有一个函数(我称之为foo)修改了一个列表(我称之为my_list)。 foo并不总是想以同样的方式修改my_list;它的行为应该受到其他参数的影响(我称之为other_inputs)。这是一些伪代码:

def foo(my_list, other_inputs):
    for input in other_inputs:
        my_list.bar(input)
    return my_list

我可以看到两种格式化other_input的方法。

我可以使用* args:

def foo(my_list, *other_inputs):
    for input in other_inputs:
        my_list.bar(input)
    return my_list

或者,我可以将other_inputs设为列表,默认为空:

def foo(my_list, other_inputs=[]):
    for input in other_inputs:
        my_list.bar(input)
    return my_list

我在我的机器上测试了它,两个选项似乎做同样的事情。哪个更好?

(假设这个foo()被多次调用,每次从一些外部源读入一个新的other_input。同时假设other_inputs永远不会在外部读取之间以任何其他方式附加或突变,所以{{3不是问题。)

2 个答案:

答案 0 :(得分:1)

由于您正在从其他来源阅读viewDidLoad,因此您可能已经有了一个序列。这支持第二种方法:

- (void)viewDidLoad {

   [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationEnteredForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];

}

- (void)applicationEnteredForeground:(NSNotification *)notification {

  // do stuff...

}

但是,您仍然可以使用第一种方法并使用

调用other_inputs
def foo(my_list, other_inputs=None):
    if other_inputs is not None:
        # Assume other_inputs is some type of iterable
        for input in other_inputs:
            my_list.bar(input)
    return my_list

这主要是一个偏好问题。

答案 1 :(得分:0)

显然,这两个选项都是正确的,说其中一个选项不是错误的。

如果传递给函数的所有其他参数都是相同的类型(相同的类型意味着它们都会改变输入),那么两种方法都是等价的。这只是@chepner

建议的偏好问题

但是如果有一些额外的参数(比如预期的输出长度)将与其他参数不同地使用,那么明确地使用list将是更好的设计。