正在numpy的数组引用传递? [英] Are numpy arrays passed by reference?

查看:329
本文介绍了正在numpy的数组引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到一个事实,即 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆