參數的傳遞模式

python中參數的傳遞模式

Posted by 劉啟仲 on Thursday, December 10, 2020

variable 跟 value 談起

variable 與其 儲存(參考)的 value (object) 是兩個完全不同的東西:

variable 是一個抽象的概念,value 是一個實際存在的資料

variable 不是其對應的 value,vairable 儲存(參考)其對應的 value

x = 5

x 是 variable,他參考到5的個數字,但是 x 並不是等於 5,可以把它想成,講到美國總統,就會想到拜登,這只是一個互相的指涉關係。

傳值(pass by value), 傳址(pass by reference)

簡單的說,就是有沒有複製或產生的動作

  • Pass by value: 會在不同的位址產生或複製一個新的

  • Pass by reference: 將自己的位址指向過去

在Python中所有的東西都是物件(Object)

>>> x = 5
>>> dir(x)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> y = 'larry'
>>> dir(y)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Python 中則是 pass by object reference or pass by sharing

def f(y):
	y.append(1)
x = [0]
f(x)
print(x) # [0,1]

x, y 所指向的是同一個物件,所以用物件所定義的方法去修改位址物件,會造成兩邊看到的東西都會被修改。

def f1(y):
	y += 1
x = 4
f(x)
print(x) # 4

這會變成 dynamic binding。

dynamic binding : binding在執行時中會完成或者允許在執行時中改變。

>>> a = 5
>>> id(a)
140035495798656
>>> a = 6
>>> id(a)
140035495798688
>>> id(5)
140035495798656
>>> id(6)
140035495798688

有用到 = 就會重新賦值