Where is the default parameter in Python function

后端 未结 5 1547
情深已故
情深已故 2021-01-05 08:52

I think many people have seen the python\'s function which receives default parameters. For example:

def foo(a=[]):
    a.append(3)
    return a
5条回答
  •  借酒劲吻你
    2021-01-05 09:27

    I have found an interesting situation: in python 2.5.2 version, try the function 'foo()'

    >>> foo()
    [1]
    >>> foo()
    [1]
    >>> foo()
    [1]
    

    Because the objects of the function called are different:

    >>> id(foo())
    4336826757314657360
    >>> id(foo())
    4336826757314657008
    >>> id(foo())
    4336826757314683160
    

    In 2.7.2 version:

    >>> foo()
    [1]
    >>> foo()
    [1, 1]
    >>> foo()
    [1, 1, 1]
    

    In this case, the object is the same each time calling the function:

    >>> id(foo())
    29250192
    >>> id(foo())
    29250192
    >>> id(foo())
    29250192
    

    Is it a problem of different versions?

提交回复
热议问题