简体   繁体   English

我对Python3.6中默认参数值的困惑

[英]My confusion about default argument values in Python3.6

Here are two pieces of codes which were under the standard of python3.6. 这是python3.6标准下的两段代码。 And they are the examples in the docs of python3.6(tutorial, page25). 它们是python3.6(tutorial,page25)文档中的示例。 The first is: 第一个是:

def f(a, L=[]):
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))

the result: 结果:

[1]
[1, 2]
[1, 2, 3]

the second: 第二:

def f(a, L = None):
    if L is None:
        L = []
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))

the result: 结果:

[1]
[2]
[3]

So, in the second piece of code, i am confused that after print(f(1)) was executed, print(f(2)) would pass a = 2 and L=[1] to the f() , but why f() didn't get the L=[1] ? 因此,在第二段代码中,我感到困惑的是,在执行print(f(1))之后, print(f(2))会将a = 2L=[1]传递给f() ,但是为什么f()没有得到L=[1]吗? If L = None in the second piece of code defines the L to None every time when the f() was called, but why L = [] in the first piece of code don't define L to [] 如果第二段代码中的L = None则每次调用f()时都将L定义为None ,但是为什么第一段代码中的L = []却没有将L定义为[]

Those two examples show how default arguments work behind the scenes: the first one demostrates that default arguments 'live' inside the function definition. 这两个示例显示了默认参数在后台的工作方式:第一个演示了默认参数在函数定义内部的“实时”运行。 Meaning: that the value for L in the first function will only ever be reset if you overwrite the whole function with a def section. 含义:只有在用def节覆盖整个函数时,才会重置第一个函数中的L值。

The Same is true for the second implementation BUT since it's None: you have to initialize it while the function body is executed. 对于第二个实现BUT,情况也是如此,因为它为None:必须在执行函数主体时对其进行初始化。 This leads to a fresh list every time the function is called. 每次调用该函数都会产生一个新列表。

This behaviour can be confusing and lead to strange results which is why i heard from most sources that it is best to avoid the first option and work with None default args. 这种行为可能会造成混乱,并导致奇怪的结果,这就是为什么我从大多数消息来源得知,最好避免使用第一个选项并使用None default args。

Hope i could clear things up a bit. 希望我能把事情弄清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM