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 [:] =
#2
12
You need to mutate instead of rebinding, with slice-assigning.
您需要使用切片分配进行变异而不是重新绑定。
psswd[:] = number[:]
#3
6
number = ['0','1','2']
def foo(psswd):
psswd[:] = number # swap the slice around here
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd
#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 [:] =
#2
12
You need to mutate instead of rebinding, with slice-assigning.
您需要使用切片分配进行变异而不是重新绑定。
psswd[:] = number[:]
#3
6
number = ['0','1','2']
def foo(psswd):
psswd[:] = number # swap the slice around here
if __name__ == '__main__':
psswd = []
foo(psswd)
print psswd