函数参数体中定义的列表是否充当 python 中的静态变量?

Does a list defined in a functions parameter body acts as a static variable in python?

在这里,列表被定义为函数参数中的局部变量foo,但我很困惑为什么即使重复调用列表仍然记得它以前的值,为什么它表现得像静态变量?

def foo(character,my_list = []):
    my_list.append(character)
    print(my_list)

foo("a")
foo('b')
foo('c')

----输出----

['a']
['a','b']
['a','b','c']

这是common gotchas之一:

Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

当您将可变值定义为默认参数时,python 所做的是这样的:

default_list = []
def foo(character, my_list=default_list):
    my_list.append(character)

任何其他可变类型都会发生同样的情况(例如dict)。 您可以在这里找到非常详细的解释:https://docs.quantifiedcode.com/python-anti-patterns/correctness/mutable_default_value_as_argument.html

将空列表作为列表默认值的一种方法可以是:

def foo(character, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(character)