[英]python pass list as function parameter
folks, 乡亲,
The result of the following code is [] Why is it not ['0','1','2']? 以下代码的结果是[]为什么不是['0','1','2']? If I want to make psswd equal to number in the function foo, what should I do? 如果我想在函数foo中使psswd等于数字,我该怎么办?
number = ['0','1','2']
def foo(psswd):
psswd = number[:]
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd
您需要使用切片分配进行变异而不是重新绑定。
psswd[:] = number[:]
number = ['0','1','2']
def foo(psswd):
psswd[:] = number # swap the slice around here
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd
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
。
Ie, 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. 当你在foo
函数中执行psswd = <something>
,会创建/获取此<something>
并使本地名称psswd
指向它。 Global variable psswd
still points to the old value. 全局变量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[:] = <smething>
实际上调用了psswd.__setitem__
方法,因此修改了本地名称psswd
引用的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.