What is the scope of a defaulted parameter in Python?

前端 未结 7 1552
攒了一身酷
攒了一身酷 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 05:01

    The scope of the L variable is behaving as you expect.

    The "problem" is with the list you're creating with []. Python does not create a new list each time you call the function. L gets assigned the same list each time you call which is why the function "remembers" previous calls.

    So in effect this is what you have:

    mylist = []
    def f(a, L=mylist):
        L.append(a)
        return L
    

    The Python Tutorial puts it this way:

    The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

    and suggests the following way to code the expected behaviour:

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

提交回复
热议问题