举栗子:
def gen_list_with(elements = [], e=None):
elements.append(e)
return elements
rs = gen_list_with( e = 'world')
print(rs)
rs = gen_list_with(e = 'python')
print(rs)
//输出
['world']
['world', 'python']
我疑惑的是:
1. 方法或函数的形参都是局部的,随着执行完毕,出栈后对应的执行环境都会被销毁,为什么还会出现这种情况呢?
2. 这种情况在给 elements 指定值的情况下会消除, 为什么呢? 比如:
rs = gen_list_with(elements = ['init'], e = 'world')
rs = gen_list_with(e = 'python')
print(rs)
//输出
['python']
我只知道是因为函数形参使用了可变对象的原因, 但是为什么这么设计, 暂时还没有找到比较权威的说明,麻烦大家给解答一下, 或者给我一份官方或 python 作者这么设计的原因说明文档, 谢谢了