What is the scope of a defaulted parameter in Python?

前端 未结 7 1544
攒了一身酷
攒了一身酷 2020-12-13 04:34

When you define a function in Python with an array parameter, what is the scope of that parameter?

This example is taken from the Python tutorial:

de         


        
7条回答
  •  [愿得一人]
    2020-12-13 04:48

    The scope is as you would expect.

    The perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to [].

    The list is stored in f.func_defaults.

    def f(a, L=[]):
        L.append(a)
        return L
    
    print f(1)
    print f(2)
    print f(3)
    print f.func_defaults
    f.func_defaults = (['foo'],) # Don't do this!
    print f(4)
    

    Result:

    [1]
    [1, 2]
    [1, 2, 3]
    ([1, 2, 3],)
    ['foo', 4]
    

提交回复
热议问题