python传递列表作为函数参数
folks,
乡亲,
The result of the following code is [] Why is it not ['0','1','2']? If I want to make psswd equal to number in the function foo, what should I do?
以下代码的结果是[]为什么不是['0','1','2']?如果我想让psswd等于函数foo中的数字,我该怎么办?
number = ['0','1','2']
def foo(psswd):
psswd = number[:]
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd
3 个解决方案
#1
1
Your code:
你的代码:
number = ['0','1','2']
def foo(psswd):
psswd = number[:]
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd
psswd = number[:]
rebinds local variable psswd
with a new list.
psswd = number [:]用新列表重新绑定局部变量psswd。
I.e., when you do foo(psswd)
, function foo
is called, and local variable passwd
inside it is created which points to the global list under the same name.
即,当你执行foo(psswd)时,会调用函数foo,并在其中创建局部变量passwd,该变量指向同名的全局列表。
When you do psswd = <something>
inside foo
function, this <something>
is created/got and local name psswd
is made to point to it. Global variable psswd
still points to the old value.
当你在foo函数中执行psswd =
If you want to change the object itself, not the local name, you must use this object's methods. psswd[:] = <smething>
actually calls psswd.__setitem__
method, thus the object which is referenced by local name psswd
is modified.
如果要更改对象本身而不是本地名称,则必须使用此对象的方法。 psswd [:] =
更多相关文章
- 用python写MapReduce函数——以WordCount为例
- Python基础(4) - 变量
- python闭包变量迟邦定
- Python内置函数介绍
- 判断变量是否是DataFrame 或者 Series
- Python学习之路:函数的非固定参数
- 函数参数中裸星号的目的是什么?
- 创建单独的函数而不是一个大的缓慢处理时间?
- Python:lambda表达式实现求两个变量的最大值