Python 中的引數如何按值或按引用傳遞?


Python 使用一種名為“按物件呼叫”的機制,有時也稱為“按物件引用呼叫”或“按共享呼叫

如果將不可變引數(如整數、字串或元組)傳遞給函式,則傳遞行為就像按值呼叫。但如果傳遞的是可變引數,情況就不同了。

Python 語言中所有引數 (argument) 都按引用傳遞。這意味著:如果你在函式內更改一個引數指向的內容,此更改在呼叫函式中也會反映出來。

示例

student={'Archana':28,'krishna':25,'Ramesh':32,'vineeth':25}
def test(student):
   new={'alok':30,'Nevadan':28}
   student.update(new)
   print("Inside the function",student)
   return
test(student)
print("outside the function:",student)

輸出

Inside the function {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}
outside the function: {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}

更新於:2019-7-30

13K+ 瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.