Maison >développement back-end >Tutoriel Python >Python 使用 list 作为函数参数时,参数是否会初始化?
看到了这样一段代码:
def foo(a, b=[]): b.append(a) print b
<code class="language-python"><span class="o">>>></span> <span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">bar</span><span class="o">=</span><span class="p">[]):</span>
<span class="o">...</span> <span class="k">return</span> <span class="n">bar</span>
<span class="o">>>></span> <span class="n">foo</span><span class="o">.</span><span class="n">func_name</span>
<span class="s">'foo'</span>
<span class="o">>>></span> <span class="n">foo</span><span class="o">.</span><span class="n">func_defaults</span>
<span class="p">([],)</span>
<span class="o">>>></span> <span class="n">foo</span><span class="p">()</span> <span class="ow">is</span> <span class="n">foo</span><span class="o">.</span><span class="n">func_defaults</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="bp">True</span>
</code>
官方文档解释在这里:default args 的求值是在定义的时候,只做一次<code class="language-text">>>> def f(a, b=[]):
... b.append(a)
... print b
...
>>> f(1)
[1]
>>> f(1)
[1, 1]
>>> def f(a, b=None):
... b = b if b is not None else []
... b.append(a)
... print b
...
>>> f(1)
[1]
>>> f(1)
[1]
>>> f(1)
[1]
>>> a = []
>>> b = []
>>> a.append(1)
>>> b
[]
>>>
</code>
啥都不用说,加一个id()输出b的所谓的地址,你就明白了<code class="language-python"><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">k</span><span class="p">,</span><span class="n">v</span><span class="p">,</span> <span class="n">fdict</span><span class="o">=</span><span class="p">{}):</span>
<span class="n">fdict</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">v</span>
<span class="k">print</span> <span class="n">fdict</span>
<span class="n">foo</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="n">foo</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">)</span>
</code>