Python 函數參數問題

來源:互聯網
上載者:User

標籤:

Python的傳遞究竟是值傳遞還是引用傳遞?

在回答這個問題之前,需要知道python中的變數只是一個對象的引用。賦值操作不會改變對象指向的內容,而是把變數從一個對象的引用,改為指向另一個對象的引用。對一個變數重新複製後,複製前後的變數id會發生改變。而在變數直接進行操作情況,分可變對象(list dict...)和不可變對象(int str tuple...)。前者不會改變,而後者則會改變,由於原始的不能改變,只能返回一個新值並賦值給該變數。

In [1]: i = 1In [2]: id(i)Out[2]: 31122120LIn [3]: i = 5In [4]: id(i)Out[4]: 31122024LIn [5]: a = [1,2,3]In [6]: id(a)Out[6]: 62749960LIn [7]: a = [23]In [8]: id(a)Out[8]: 62757576LIn [9]: i = 5In [10]: id(i)Out[10]: 31122024LIn [11]: i += 1In [12]: id(i)Out[12]: 31122000LIn [13]: id(a)Out[13]: 62757576LIn [14]: a.append(5)In [15]: id(a)Out[15]: 62757576L

賦值無法改變函數內或者函數外,變數引用地址的對象。因此python函數是按引用傳遞,傳遞的是對象的引用。至於會不會修改這個參數,取決於對變數進行的操作和變數是 可變變數還是不可變變數。

def f(n,x):    n = 3    x.append(7)    #x = [4,5,6]    print "In f()",n,xif __name__ == "__main__":    n = 1    x = [0,1,2]    print "Before:",n,x    f(n,x)    print "After:",n,x>>> Before: 1 [0, 1, 2]In f() 3 [0, 1, 2, 7]After: 1 [0, 1, 2, 7]def f(n,x):    n += 3    x.append(7)    #x = [4,5,6]    print "In f()",n,xif __name__ == "__main__":    n = 1    x = [0,1,2]    print "Before:",n,x    f(n,x)    print "After:",n,xBefore: 1 [0, 1, 2]In f() 4 [0, 1, 2, 7]After: 1 [0, 1, 2, 7]def f(n,x):    n = 3    #x.append(7)    x = [4,5,6]    print "In f()",n,xif __name__ == "__main__":    n = 1    x = [0,1,2]    print "Before:",n,x    f(n,x)    print "After:",n,xBefore: 1 [0, 1, 2]In f() 3 [4, 5, 6]After: 1 [0, 1, 2]

 

Python 函數參數問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.