論證傳遞和可變性

首先,一些術語:

  • argument( 實際引數): 傳遞給函式的實際變數;
  • parameter( 形式引數): 函式中使用的接收變數。

在 Python 中,引數通過*賦值*傳遞 (與其他語言相反,其中引數可以通過值/引用/指標傳遞)。

  • 變數引數將改變引數(如果引數的型別是可變的)。

    def foo(x):        # here x is the parameter
        x[0] = 9       # This mutates the list labelled by both x and y
        print(x)
    
    y = [4, 5, 6]
    foo(y)             # call foo with y as argument
    # Out: [9, 5, 6]   # list labelled by x has been mutated
    print(y)           
    # Out: [9, 5, 6]   # list labelled by y has been mutated too
    
  • 重新分配引數不會重新分配引數。

    def foo(x):        # here x is the parameter, when we call foo(y) we assign y to x
        x[0] = 9       # This mutates the list labelled by both x and y
        x = [1, 2, 3]  # x is now labeling a different list (y is unaffected)
        x[2] = 8       # This mutates x's list, not y's list
    
    y = [4, 5, 6]      # y is the argument, x is the parameter
    foo(y)             # Pretend that we wrote "x = y", then go to line 1
    y
    # Out: [9, 5, 6]
    

在 Python 中,我們真的不給變數賦值,而不是我們結合** (即分配,附加)變數(被視為名稱 )的物件。**

  • 不可變: 整數,字串,元組等。所有操作都會複製。
  • 可變: 列表,詞典,集合等。操作可能會也可能不會發生變異。
x = [3, 1, 9]
y = x
x.append(5)    # Mutates the list labelled by x and y, both x and y are bound to [3, 1, 9]
x.sort()       # Mutates the list labelled by x and y (in-place sorting)
x = x + [4]    # Does not mutate the list (makes a copy for x only, not y)
z = x          # z is x ([1, 3, 9, 4])
x += [6]       # Mutates the list labelled by both x and z (uses the extend function).
x = sorted(x)  # Does not mutate the list (makes a copy for x only).
x
# Out: [1, 3, 4, 5, 6, 9]
y
# Out: [1, 3, 5, 9]
z
# Out: [1, 3, 5, 9, 4, 6]