9月1日学习笔记之python常见错误

默认参数值 


这是对于一个初学者常犯的错误,甚至于一些高级开发人员也会遇到,因为他们并不了解 Python 中的 names. 

Python代码 
  1. def bad_append(new_item, a_list=[]):  
  2.     a_list.append(new_item)  
  3.     return a_list  


这里的问题是,a_list是一个空列表,默认值是在函数定义时进行初始化。因此,每次调用该函数,你会得到不相同的默认值。尝试了好几次: 

Python代码 
  1. >>> print bad_append('one')  
  2. ['one']  
  3. >>> print bad_append('two')  
  4. ['one''two']  


列表是可变对象,你可以改变它们的内容。正确的方式是先获得一个默认的列表(或dict,或sets)并在运行时创建它。 

Python代码 
  1. def good_append(new_item, a_list=None):  
  2.     if a_list is None:  
  3.         a_list = []  
  4.     a_list.append(new_item)  
  5.     return a_list  



 

原文:http://blog.csdn.net/marty_fu/article/details/7679297

1. 循环语句

[python] view plaincopy
  1. for i in range(3):  
  2.     print i  

在程序里面经常会出现这类的循环语句,Python的问题就在于,当循环结束以后,循环体中的临时变量i不会销毁,而是继续存在于执行环境中。

还有一个python的现象是,python的函数只有在执行时,才会去找函数体里的变量的值。

[python] view plaincopy
  1. flist = []  
  2. for i in range(3):  
  3.     def foo(x): print x + i  
  4.     flist.append(foo)  
  5. for f in flist:  
  6.     f(2)  
可能有些人认为这段代码的执行结果应该是2,3,4.但是实际的结果是4,4,4。这是因为当把函数加入flist列表里时,python还没有给i赋值,只有当执行时,再去找i的值是什么,这时在第一个for循环结束以后,i的值是2,所以以上代码的执行结果是4,4,4.
解决方法也很简单,改写一下函数的定义就可以了。
[python] view plaincopy
    1. for i in range(3):  
    2.     def foo(x,y=i): print x + y  
    3.     flist.append(foo)  
posted @ 2013-09-01 20:29  blue_whale  阅读(135)  评论(0)    收藏  举报