Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4469262
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Python/Ruby

2015-01-01 21:11:15

def foo(x=[]): x.append(1); print(x)
foo(); foo()
得到:
[1]
[1, 1]

第一次调用foo() 得到x =[] ,然后x = [1],x指向列表[1]内存中的地址。
但是第二次调用foo() , 不执行x = []

参考 Python 官方 Tutorial 中的内容

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:




原文地址:http://blog.csdn.net/delphiwcdj/article/details/5719470
Python Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

[1] 
The default values are evaluated at the point of function definition in the defining scope, so that will print 5

  1. >>> def f(arg=i):  
  2.     print arg  
  3.       
  4. >>> f()  
  5. 5  
  6. >>> i=2  
  7. >>> f  
  8.   
  9. >>> f()  
  10. 5  
  11. >>> i=5  
  12. >>> i  
  13. 5  
  14. >>> def f(arg=i):  
  15.     print 'i=', i  
  16.       
  17. >>> f()  
  18. i= 5  
  19. >>> i=6  
  20. >>> f()  
  21. i= 6  
  22. >>>   


[2] 
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

  1. >>> def f(a, L=[]):  
  2.     L.append(a)  
  3.     return L  
  4. >>> print f(1)  
  5. [1]  
  6. >>> print f(2)  
  7. [1, 2]  
  8. >>> print f(3)  
  9. [1, 2, 3]  
  10. >>>   
  11. # modified as following  
  12. >>> def f(a, L=None):  
  13.     if L is None:  
  14.         L=[]  
  15.     L.append(a)  
  16.     return L  
  17. >>> f(1)  
  18. [1]  
  19. >>> f(2)  
  20. [2]  
  21. >>> f(3)  
  22. [3]  
  23. >>>  


阅读(640) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~