论证传递和可变性
首先,一些术语:
- 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]