有什么区别? numpy.Array通过Ref
为什么我们在这些NP array上有两种不同的行为?
def pass_by_ref(A: np.array):
A = np.ones((2,2))
return A
def pass_by_ref_sideEffect(A: np.array):
A[0][0] = 2
return A
A = np.zeros((2,2))
B = pass_by_ref(A)
print("A =\n", A)
print("B =\n", B)
C = pass_by_ref_sideEffect(A)
print("A =\n", A)
print("C =\n", C)
输出:
A =
[[0. 0.]
[0. 0.]]
B =
[[1. 1.]
[1. 1.]]
A =
[[2. 0.]
[0. 0.]]
C =
[[2. 0.]
[0. 0.]]
为什么我们会对pass_by_ref_sideeffect而不是pass_by_ref产生副作用?
Why do we have two different behaviors on these np.array?
def pass_by_ref(A: np.array):
A = np.ones((2,2))
return A
def pass_by_ref_sideEffect(A: np.array):
A[0][0] = 2
return A
A = np.zeros((2,2))
B = pass_by_ref(A)
print("A =\n", A)
print("B =\n", B)
C = pass_by_ref_sideEffect(A)
print("A =\n", A)
print("C =\n", C)
output:
A =
[[0. 0.]
[0. 0.]]
B =
[[1. 1.]
[1. 1.]]
A =
[[2. 0.]
[0. 0.]]
C =
[[2. 0.]
[0. 0.]]
Why we have side effect on A after pass_by_ref_sideEffect and not with pass_by_ref?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与您在变量中传递的方式无关,与分配的工作方式有关。在
pass_by_ref()
此行a = np.ones((2,2))
创建一个新数组并将其分配给本地名称a
。原始数组对象仍然存在,但是a
不再指它。在另一种情况下,您是通过使用a [0] [0] = 2
将原始数组来操纵原始数组。如果您想在第一种情况下具有副作用,则分配给类似的片段:
以下是一个示例,在不传递变量中的函数中演示这一点:
This has nothing to do with how you are passing in the variable and everything to do with how assignment works. In
pass_by_ref()
this lineA = np.ones((2,2))
creates a new array and assigns it to the local nameA
. The original array object still exists, butA
no longer refers to it. In the other case you are manipulating the original array by assigning to an element of it withA[0][0] = 2
.If you want to have a side effect in the first case, then assign to a slice of A like this:
Here's an example that demonstrates this without passing variables into functions:
当Python调用该函数时,它将传递对象的引用。当您使用
a [0] [0] = 2
进行分配时,它将根据variablea
指向的对象的地址取代它写。但是,如果您使用a = np.ones(((2,2))
,将创建一个新数组并制作变量a
指向它。When Python calls the function, it passes the reference of the object. When you use
A[0][0] = 2
for assignment, it will offset according to the address of the object pointed to by variableA
, find the address to be write. But if you useA = np.ones((2, 2))
, a new array will be created and make variableA
points to it.