---
title: "Python函数参数默认值的陷阱"
author: "剑锋凛冽"
date: "2012-11-12T18:18:23Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2012-11-12T18:18:41Z"
id: 1723184
url: "https://swordboy007.iteye.com/blog/1723184"
---

阅读下面一段Python代码

 

```
def testMutablePara1(a,l=[]):
	l.append(a)
	return l
print testMutablePara1(1)
print testMutablePara1(2)
```

 初看之下，这段代码在第二次应该输出\[2]

但是运行结果却是

 

\[1]

\[1, 2]

为什么呢？

这是因为Python在处理函数定义时，除了将函数的代码定义到内存中以外，同时会将默认值参数的值作为对象存放到内存中，以后每次调用都使用的都是内存中该默认值的对象，所以当参数默认值是mutable对象，如list、dict等时，每次调用都有可能使结果出现错误的结果。

替代的方法是，将默认值参数用None，而在使用之前显式地进行初始化

如下所示

 

```
def testMutablePara2(a,l=None):
	if l==None:
		l=[]
	l.append(a)
	return l
print testMutablePara2(1)
print testMutablePara2(2)
```

 这样就能输出符合预期的结果了。

 

参考[http://www.cnblogs.com/ukessi/archive/2010/01/25/python-function-default-parameter-value-problem.html](http://www.cnblogs.com/ukessi/archive/2010/01/25/python-function-default-parameter-value-problem.html)