Default values for arguments [duplicate]

醉酒当歌 提交于 2019-12-02 10:48:59

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!