首页 >后端开发 >Python教程 >Python 使用 list 作为函数参数时,参数是否会初始化?

Python 使用 list 作为函数参数时,参数是否会初始化?

WBOY
WBOY原创
2016-06-06 16:23:571436浏览

看到了这样一段代码:

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 的求值是在定义的时候,只做一次
4. More Control Flow Tools

但是……
<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的所谓的地址,你就明白了

Python 使用 list 作为函数参数时,参数是否会初始化? no, def foo(a=[]) 这种函数参数写法叫 参数默认值,只会在函数声明是初始化一次。之后不会再变了。

note, 建议了解一下 def foo(a=[])和 foo(a=[])的区别:前者是参数默认值,后者是keyword arguments. 还有这种def foo(*args, **kargs) 和 这种 foo(*args, **kargs), 都是有细微区别的。 不会的, 默认值之间是共享的, 只会创建一次, 并不会每次创建一个新的对象. 也就是说使用可变对象作为函数的默认值时会导致函数的混乱. 同理使用字典作为默认参数,会得出类似的返回.
<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>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn