python list 参数传递方式
2017-11-07 19:18
204 查看
定义一个方法,接收一个 id参数和一个 list 参数
def test(id, ids=[]): if id: ids.append(id) print ids test(id=1) test(id=2)
打印结果
[1] [1, 2]
分析原因
上面方法的定义方式跟下面是一样的,相当于是参数引用的是一个全局变量,所以它的值一直在累加ids = [] def test(id, ids): if id: ids.append(id) print ids test(id=1) test(id=2)
解决办法:默认list参数为None,在需要的时候再去定义
def test(id, ids=None): if id: ids = list() ids.append(id) print ids test(id=1) test(id=2)
相关文章推荐
- python函数的四种参数传递方式
- 详解Python函数可变参数定义及其参数传递方式
- python函数的参数传递方式
- python传递参数方式小结
- python中参数的传递的list形式和dict的区分
- python函数的四种参数传递方式
- std::list/vector 作为函数参数的传递方式
- Python里的函数参数传递方式(表现为非值传递也非引用传递)
- 关于Python函数参数传递方式--值传递?引用传递!
- Python函数参数传递方式(call by object reference)以及一致性
- Python函数可变参数定义及其参数传递方式实例详解
- Python函数可变参数定义及其参数传递方式详解
- SpringMVC参数传递方式list,map
- python传递参数方式小结
- Python 参数传递方式
- Python 函数参数传递方式
- 初学python--参数传递方式
- Python--函数参数的传递方式
- python参数传递方式
- Python中函数的参数传递方式