简体   繁体   中英

My confusion about default argument values in Python3.6

Here are two pieces of codes which were under the standard of python3.6. And they are the examples in the docs of 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] ? 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 []

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.

The Same is true for the second implementation BUT since it's None: you have to initialize it while the function body is executed. 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.

Hope i could clear things up a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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