Python 值傳遞 {Pass by Value} 和引用傳遞 {Pass by Reference}
- 1. Mutable Objects and Immutable Objects in Python (Python 可變對象和不可變對象)
- 2. Pass by Value and Pass by Reference
- 2.1. What is Pass by Value in Python?
- 2.2. What is Pass by Reference in Python?
- References
Data model
https://docs.python.org/3/reference/datamodel.html
1. Mutable Objects and Immutable Objects in Python (Python 可變對象和不可變對象)
The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.
值可以改變的對象被稱為可變對象;值不可以改變的對象就被稱為不可變對象。(一個不可變容器對象如果包含對可變對象的引用,當后者的值改變時,前者的值也會改變;但是該容器仍屬于不可變對象,因為它所包含的對象集是不會改變的。因此,不可變并不嚴格等同于值不能改變,實際含義要更微妙。) 一個對象的可變性是由其類型決定的;例如,數字、字符串和元組是不可變的,而字典和列表是可變的。
Python 中有兩種類型的對象:可變對象 (mutable objects) 和不可變對象 (immutable objects)。
-
可變對象在創建后可以被修改。列表 (list)、字典 (dictionary)、集合 (set) 等是可變對象。
-
不可變對象在創建后不能被修改。整數 (integer)、浮點數 (float)、字符串 (string)、元組 (tuple) 等是不可變對象。
在 Python 中,變量是對對象的引用。當你將一個值賦值給變量時,實際上是在創建一個指向表示該值的對象的引用。
2. Pass by Value and Pass by Reference
Pass by Reference | Pass by Value | |
---|---|---|
Object Type | Mutable (list, dict, etc.) | Immutable (int, str, etc.) |
Passed | Reference to object | Reference to object |
Modify in function? | Yes (affects original) | No (new object created) |
Behavior | Like aliasing | Like copying |
2.1. What is Pass by Value in Python?
2.2. What is Pass by Reference in Python?
References
[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] Pass by reference vs value in Python, https://www.geeksforgeeks.org/python/pass-by-reference-vs-value-in-python/