python 易出错总结

来源:互联网 发布:数据库账号管理办法 编辑:程序博客网 时间:2024/05/17 08:33

1.Default Parameter Values

This is a common mistake that beginners often make.  Even more advanced programmers make this mistake if they don't understand Python names.

def bad_append(new_item, a_list=[]):    a_list.append(new_item)    return a_list
The problem here is that the default value of a_list, an empty list, is evaluated at function definition time.  So every time you call the function, you get thesame default value.  Try it several times:
>>> print bad_append('one')['one']
>>> print bad_append('two')['one', 'two']
Lists are a mutable objects; you can change their contents.  The correct way to get a default list (or dictionary, or set) is to create it at run time instead,inside the function:
def good_append(new_item, a_list=None):    if a_list is None:        a_list = []    a_list.append(new_item)    return a_list

 

2.

原创粉丝点击