使用以下代码
def test(n):
n=n*2
print("inside test",n)
n=[9]
print("before the call", n)
test(n)
print("after the call", n) 它的输出是:
before the call [9]
inside test [9, 9]
after the call [9]我认为在函数中传递列表参数是通过引用和修改调用parameters.It的方式进行的,这里的情况不是这样的: passing。我原以为:
before the call [9]
inside test [9, 9]
after the call [9, 9]如果我使用append方法而不是n=n*2,效果是可以的。有人能澄清这一点吗?
发布于 2016-12-13 12:51:31
它是关于可变或不变的类型和值或引用参数。Python传递“参考”,但不是真正的(详见:https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/)
>>> def update_list(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)
>>> toto = ["one"]
>>> update_list(toto)
got ['one']
changed to ['one', 'four']
>>> print(toto)
['one', 'four']
>>> def new_list(the_list):
print('got', the_list)
the_list = the_list + ["four"]
print('changed to', the_list)
>>> toto = ["one"]
>>> new_list(toto)
got ['one']
changed to ['one', 'four']
>>> print(toto)
['one']发布于 2016-12-13 12:42:23
这一行n = n*2在您的test()函数中创建了一个新的局部变量n,这就是为什么外部变量不被更改的原因。看看下面的例子:
>>> def test(n):
... print(id(n))
... n = n*2
... print(id(n))
... print("inside test", n)
...
>>> def test2(n):
... print(id(n))
... n.append(2)
... print(id(n))
... print("inside test2", n)
...
>>> n = [9]
>>> id(n)
49744472
>>>
>>> test(n)
49744472
49744752
('inside test', [9, 9])
>>>
>>> test2(n)
49744472
49744472
('inside test2', [9, 2])在test()中,我们有两个不同的ids:49744472用于param n,49744752用于(局部变量 n )。在test2()函数中,打印相同的id,这意味着在函数中更改相同的param n。
发布于 2016-12-13 12:45:19
在python中,将传递给函数的参数引用为值传递/引用传递通常是令人困惑的。
n=9
上述语句将n绑定到包含值为9的单个元素的List对象(本例中为9)。
当n=n*2时,这将创建一个新的列表并绑定到一个变量,该变量是函数作用域的局部变量。
https://stackoverflow.com/questions/41121246
复制相似问题