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/