numpy 矩陣在作為函數參數傳遞時的奇怪點


numpy 矩陣在作為函數參數傳遞時的奇怪點

import numpy as np

class simpleNet:
    def __init__(self):
        self.W = np.array([1, 2, 3])


def f(w):
    w[1] = 100
    w[0] = 1212
    print(id(w))


# 定義 test 對象打印其地址
test = simpleNet()
print(id(test.W))

# 作為參數 傳遞給 f
f(test.W)

print(test.W)

輸出:

image-20210608152306319

我們可以看到,這是一種引用的傳遞方式.

但如果將函數 f 修改為這樣:

import numpy as np

class simpleNet:
    def __init__(self):
        self.W = np.array([1, 2, 3])


def f(w):
    w = w + 1
    print(id(w))


# 定義 test 對象打印其地址
test = simpleNet()
print(id(test.W))

# 作為參數 傳遞給 f
f(test.W)

print(test.W)

輸出:

image-20210608152508688

可以看到,此時傳遞的就是單純地值的傳遞,因為 test.W 和 函數 f里的w地址是不一樣的

此外我還驚訝地發現了這樣的一個情況:

def f(w):
    print("傳遞過來但未修改的w\t", id(w))
    w = w + 1
    print("傳遞過來但修改了的w\t", id(w))


w = 5
print("剛創建的w\t\t\t", id(w))

f(w)

輸出:

image-20210608153044245


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM