(初学者求解答)python默认参数

hewu51400206 2014-05-20 11:30:30
python tutorial 里面有这么一段话:


If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L


这样究竟是怎么做到默认参数不被后续调用共享呢?

另外,按下面这么编写也是能做到默认参数不被后续共享。求原因
Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.

>>> def f(a,L=[]):
... if L==[]:
... L=[]
... L.append(a)
... return L
...
>>> f(1)
[1]
>>> f(2)
[2]
>>> f(3)
[3]
>>>

...全文
115 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Keal 2014-05-20
  • 打赏
  • 举报
回复
你的方法和python tutorial的效果是一样的, 当不传L时,都是每次调用函数时先把L清空。 当函数f被调用结束后,L所占的那块内存并没有被释放(L没有从内存中删去)。所以当再次调用函数时,使用的还是上次的那个L的内存,如果你不把L重设为空的话,调用append后会在L的末尾加上一个元素,使得 f(2)返回[1,2] f(3)返回[1,2,3]了 代码: def f1(a, L=None): if L is None: L = [] print id(L) L.append(a) return L def f2(a, L=[]): if L == []: L = [] print id(L) L.append(a) return L print f1(1) print f1(2) print f1(3) print f2(1) print f2(2) print f2(3) 输出: 141323916 [1] 141323916 [2] 141323916 [3] 141323916 [1] 141323916 [2] 141323916 [3]

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧