gpt4 book ai didi

Python - 为什么按值传递的 ndarray 在函数外发生变化?

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:57 26 4
gpt4 key购买 nike

<分区>

我有以下功能:

def a_function(foo):
bar = foo
print("bar1: ", bar, id(foo))
bar[0] = foo[2]
print("bar2: ", bar, id(foo))

以列表作为参数调用:

foo = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print("foo1: ", foo, id(foo))
a_function(foo[:])
print("foo2: ", foo, id(foo))

输出:

foo1:  [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901565768
bar1: [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901566472
bar2: [2, 1, 2, 3, 4, 5, 6, 7, 8] 140118901566472
foo2: [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901565768

以 ndarray 作为参数调用:

foo = np.arange(0,9)
print("foo1: ", foo, id(foo))
a_function(foo[:])
print("foo2: ", foo, id(foo))

输出:

foo1:  [0 1 2 3 4 5 6 7 8] 139814139381760
bar1: [0 1 2 3 4 5 6 7 8] 139814115258000
bar2: [2 1 2 3 4 5 6 7 8] 139814115258000
foo2: [2 1 2 3 4 5 6 7 8] 139814139381760

我将它作为副本传递 foo[:] 甚至在函数内部再次复制,而且它有自己的 ID。然而,当 foo2 是一个 ndarray 时,它在函数范围之外改变了它的值。这怎么可能?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com