9月1日学习笔记之python常见错误
默认参数值
这是对于一个初学者常犯的错误,甚至于一些高级开发人员也会遇到,因为他们并不了解 Python 中的 names.
- def bad_append(new_item, a_list=[]):
- a_list.append(new_item)
- return a_list
这里的问题是,a_list是一个空列表,默认值是在函数定义时进行初始化。因此,每次调用该函数,你会得到不相同的默认值。尝试了好几次:
- >>> print bad_append('one')
- ['one']
- >>> print bad_append('two')
- ['one', 'two']
列表是可变对象,你可以改变它们的内容。正确的方式是先获得一个默认的列表(或dict,或sets)并在运行时创建它。
- def good_append(new_item, a_list=None):
- if a_list is None:
- a_list = []
- a_list.append(new_item)
- return a_list
原文:http://blog.csdn.net/marty_fu/article/details/7679297
1. 循环语句
- for i in range(3):
- print i
在程序里面经常会出现这类的循环语句,Python的问题就在于,当循环结束以后,循环体中的临时变量i不会销毁,而是继续存在于执行环境中。
还有一个python的现象是,python的函数只有在执行时,才会去找函数体里的变量的值。
- flist = []
- for i in range(3):
- def foo(x): print x + i
- flist.append(foo)
- for f in flist:
- f(2)
可能有些人认为这段代码的执行结果应该是2,3,4.但是实际的结果是4,4,4。这是因为当把函数加入flist列表里时,python还没有给i赋值,只有当执行时,再去找i的值是什么,这时在第一个for循环结束以后,i的值是2,所以以上代码的执行结果是4,4,4.
解决方法也很简单,改写一下函数的定义就可以了。
- for i in range(3):
- def foo(x,y=i): print x + y
- flist.append(foo)