why this python function return len=7 instead of len=6?

tin*_*x84 3 python-3.x

I got this code below, but even debugging it, I cannot understand why gives me out 7 instead of 6.

More precisely when I debudg every return gives me the expected result:

  1. first func call: ipdb> --Return-- ['a']
  2. second func call: ipdb> --Return-- ['a', 'a']
  3. third func call: ipdb> --Return-- ['a', 'a', 'a']

but at the end func() + func() + func() becomes ['a', 'a', 'a', 'a', 'a', 'a', 'a']

why is there one 'a' more???

#!/usr/bin/python
# -*- coding: utf-8 -*-

def func(par=[]):
    par.append("a")
    return par

print(len(func() + func() + func()))
Run Code Online (Sandbox Code Playgroud)

Kal*_*drr 5

执行时func() + func() + func(),Python必须将临时对象存储在堆栈上以将它们添加在一起,这意味着您的代码等效于

a = func() # returns ['a']
b = func() # returns ['a', 'a'], but variable 'a' now holds ['a', 'a'] as well!
tmp = a + b
c = func() # return ['a', 'a', 'a']
d = tmp + c
return d
Run Code Online (Sandbox Code Playgroud)

由于Mutable Default Argument的缘故,在实际添加a+bab都等于之前['a', 'a'],给您['a', 'a', 'a', 'a']4个元素,然后['a','a','a']从第3次func()调用中添加您的内容,结果得到7个元素。