参数的默认值 [英] Default values for arguments

查看:112
本文介绍了参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

最小惊讶在Python中:可变的默认参数


考虑以下函数:

  def foo(L = []):
L.append(1)
print L

每次我调用foo时,它都会打印一个比以前更多元素的新列表,例如:

b
$ b

 >>> foo()
[1]
>>> foo()
[1,1]
>>> foo()
[1,1,1]

现在考虑以下函数: / b>

  def goo(a = 0):
a + = 1
打印
code>

当多次调用它时,我们得到如下图片:

 >>> goo()
1
>>> goo()
1
>>> goo()
1

即每次通话都不会打印出更大的值。

这种看似不一致的行为背后的原因是什么?

另外,如何证明第一个例子中的反直觉行为是可能的,为什么函数在调用之间保持状态?

解决方案

当函数定义时,默认参数会被计算一次。
因此,每次调用该函数时都会得到相同的 list 对象。



每次调用第二个函数时都会得到相同的 0 对象,但由于 int 是不可变的,所以当您添加 1 ,因为新对象需要绑定到一个

 >>> ; def foo(L = []):
...打印ID(L)
... L.append(1)
...打印ID(L)
...打印L
...
>>> foo()
3077669452
3077669452
[1]
>>> foo()
3077669452
3077669452
[1,1]
>>> foo()
3077669452
3077669452
[1,1,1]



 >>> def foo(a = 0):
...打印ID(a)
... a + = 1
...打印ID(a)
...打印a
...
>>> foo()
165989788
165989776
1
>>> foo()
165989788
165989776
1
>>> foo()
165989788
165989776
1


Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

Consider the following function:

def foo(L = []):
  L.append(1)
  print L

Each time I call foo it will print a new list with more elements than previous time, e.g:

>>> foo()
[1]
>>> foo()
[1, 1]
>>> foo()
[1, 1, 1]

Now consider the following function:

def goo(a = 0):
  a += 1
  print a

When invoking it several times, we get the following picture:

>>> goo()
1
>>> goo()
1
>>> goo()
1

i.e. it does not print a larger value with every call.

What is the reason behind such seemingly inconsistent behavior?
Also, how is it possible to justify the counter-intuitive behavior in the first example, why does the function retain state between calls?

解决方案

The default arguments are evaluated once when the function is defined. So you get the same list object each time the function is called.

You'll also get the same 0 object each time the second function is called, but since int is immutable, when you add 1 as fresh object needs to be bound to a

>>> def foo(L = []):
...   print id(L)
...   L.append(1)
...   print id(L)
...   print L
... 
>>> foo()
3077669452
3077669452
[1]
>>> foo()
3077669452
3077669452
[1, 1]
>>> foo()
3077669452
3077669452
[1, 1, 1]

vs

>>> def foo(a=0):
...   print id(a)
...   a+=1
...   print id(a)
...   print a
... 
>>> foo()
165989788
165989776
1
>>> foo()
165989788
165989776
1
>>> foo()
165989788
165989776
1

这篇关于参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆