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:
ipdb> --Return-- ['a']ipdb> --Return-- ['a', 'a']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)
执行时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+b,a和b都等于之前['a', 'a'],给您['a', 'a', 'a', 'a']4个元素,然后['a','a','a']从第3次func()调用中添加您的内容,结果得到7个元素。
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |