简体   繁体   English

Python通过引用混淆传递对象

[英]Python passing object by reference confusion

Hi I seem to having issues understanding of passing object by reference in Python. 嗨,我似乎在理解通过Python引用传递对象方面遇到问题。 I understand example 1 output, but shouldn't example 2 behave in the similar way and not change the A matrix? 我了解示例1的输出,但是示例2不应以类似的方式运行并且不更改A矩阵吗?

Example 1: 范例1:

def reassign(list):
  list = [0, 1, 2]

list = [3]
reassign(list)
print(list)

Returns: [3]

Example 2: 范例2:

import numpy as np

A = np.ones((4,4))

def xyz(A):
    for i in range(4):
        A[i,i] = 0    
    return None

x = xyz(A)
print(A)

# Returns

[[0. 1. 1. 1.]
 [1. 0. 1. 1.]
 [1. 1. 0. 1.]
 [1. 1. 1. 0.]]

Passing by reference means that, when you pass a variable into the function, you don't pass the variable itself , you pass the pointer to the variable, which is copied from outside to inside the function. 通过引用传递意味着,当您将变量传递给函数时,您不会传递变量本身 ,而是将指针传递变量,该指针从函数的外部复制到内部。 In Example 1, you pass list into the function, which is a pointer to a list that contains the elements [3] . 在示例1中,将list传递给函数,该函数是指向包含元素[3]的列表的指针。 But then, immediately after, you take that variable holding the pointer to the list, and put a new pointer in it, to a new list that contains the elements [0, 1, 2] . 但是,紧接着之后,您将变量保存到列表的指针,并在其中放入新指针,以指向包含元素[0, 1, 2]的新列表。 Note that you haven't changed the list you started with - you changed what the variable referring to it referred to. 请注意,您尚未更改开始的列表,而是更改了引用该变量的变量 And when you get back out of the function, the variable you passed into the function (still a pointer to the first list) hasn't changed - it's still pointing to a list that contains the elements [3] . 当您退出该函数时,传递给该函数的变量(仍然是指向第一个列表的指针)没有改变-它仍指向包含元素[3]的列表。

In Example 2, you pass A into xyz() . 在示例2中,将A传递给xyz() Whereas in Example 1 you did something along the lines of 而在示例1中,您按照

A = something_else

here, you're doing 在这里,你在做

A[i] = something_else

This is an entirely different operation - instead of changing what the variable holding the list is pointing to, you're changing the list itself - by changing one of its elements. 这是完全不同的操作 -通过更改其元素之一,而不是更改包含列表的变量所指向的内容,而是在更改列表本身。 Instead of making A point to something else, you're changing the value that A points to by dereferencing it. 您不必通过使A指向其他值,而是通过取消引用来更改A指向的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM