numpy 数组是通过引用传递的吗? [英] Are numpy arrays passed by reference?

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

问题描述

我遇到numpy数组在多个地方通过引用传递的事实,但是当我执行以下代码时,为什么foo的行为有差异code> 和 bar

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 中,所有变量名都是引用值.

In Python, all variable names are references to values.

当 Python 计算赋值时,右边先计算左侧.arr - 3 创建一个新数组;它不会就地修改 arr.

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 使局部变量 arr 引用这个新数组.它不会修改传递给 fooarr 最初引用的值.变量名 arr 简单地绑定到新数组 arr - 3.此外,arrfoo 函数作用域内的局部变量名.一旦 foo 函数完成,就不再引用 arr 并且 Python 可以自由地对其引用的值进行垃圾收集.正如 Reti43 指出的,为了arr 的值影响 afoo 必须返回 arra 必须分配给该值:

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)

相反,arr -= 3,Python 将其转换为对 __iadd__ 特殊方法,会就地修改arr 引用的数组.

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天全站免登陆