正在numpy的数组引用传递? [英] Are numpy arrays passed by reference?
问题描述
我碰到一个事实,即 numpy的
数组通过引用在多个地方通过,但后来当我执行以下code,为什么会有之间的差异来行为富
和栏
I came across the fact that numpy
arrays are passed by reference at multiple places, but then when I execute the following code, why is there a difference between the behavior of foo
and bar
import numpy as np
def foo(arr):
arr = arr - 3
def bar(arr):
arr -= 3
a = np.array([3, 4, 5])
foo(a)
print a # prints [3, 4, 5]
bar(a)
print a # prints [0, 1, 2]
我使用python 2.7和numpy的版本1.6.1
I'm using python 2.7 and numpy version 1.6.1
推荐答案
在Python中,所有变量名是引用到值。
在Python的评估转让,右手左手侧的前侧进行评价。 改编 - 3
创建一个新的阵列;它不修改改编
原地。
When Python evaluates an assignment, the right-hand side is evaluated before the left-hand side. arr - 3
creates a new array; it does not modify arr
in-place.
ARR = ARR - 3
使得局部变量改编
引用这个新的数组。它不会修改被传递给富
最初由引用改编
的值。变量名称改编
只是被绑定到新阵列,改编 - 3
。此外,改编
是富
函数的范围局部变量名。一旦富
功能完成后,没有更多的参照改编
和Python是免费的垃圾收集它所引用的值。 <一href=\"http://stackoverflow.com/questions/11585793/are-numpy-arrays-passed-by-reference/11585878?noredirect=1#comment56288437_11585878\">As Reti43指出,为了让改编
的价值影响 A
,富
必须返回改编
和 A
必须分配给该值:
arr = arr - 3
makes the local variable arr
reference this new array. It does not modify the value originally referenced by arr
which was passed to foo
. The variable name arr
simply gets bound to the new array, arr - 3
. Moreover, arr
is local variable name in the scope of the foo
function. Once the foo
function completes, there is no more reference to arr
and Python is free to garbage collect the value it references. As Reti43 points out, in order for arr
's value to affect a
, foo
must return arr
and a
must be assigned to that value:
def foo(arr):
arr = arr - 3
return arr
# or simply combine both lines into `return arr - 3`
a = foo(a)
在此相反,改编 - = 3
,它是由Python转化为调用的 __ __ IADD
特殊方法,不修改由改编
原地。
In contrast, arr -= 3
, which Python translates into a call to the __iadd__
special method, does modify the array referenced by arr
in-place.
这篇关于正在numpy的数组引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!