使用以下代码
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]
我以为函数中的列表参数是通过引用传递并修改了调用参数的,这里不是这样:令人惊讶。我期待:
before the call [9]
inside test [9, 9]
after the call [9, 9]
如果我使用append
方法代替n=n*2
,效果就可以了。任何人都可以澄清这一点吗?
它涉及可变或不可变的类型和值或引用参数。Python通过“引用”但不是真的(有关详细信息,请参见此处:https : //jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-ntwo/)
>>> 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']
Python文档:https : //docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
一个类似的问题:如何通过引用传递变量?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句