Skip to content

Commit 3ebb200

Browse files
committed
参数传递机制
参数传递机制
1 parent d36fc34 commit 3ebb200

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Python函数参数的传递机制
2+
## 不可变对象是值传递
3+
**python中不可变对象,函数实际参数(实参)传递给形式参数(形参)的过程,实际上是把实际参数值的副本(复制品)传入函数,参数本身不会收到任何影响。**
4+
5+
```python
6+
def func(a, b):
7+
a, b = b, a
8+
# 函数内 a:2 b:1
9+
print('函数内 a:{} b:{}'.format(a, b))
10+
11+
if __name__ == '__main__':
12+
a = 1
13+
b = 2
14+
# 可以理解为是将a, b的值复制一份传入
15+
func(a, b)
16+
# 函数外 a:1 b:2
17+
print('函数外 a:{} b:{}'.format(a, b))
18+
```
19+
20+
## 可变对象是引用传递(地址传递)
21+
对于可变对象如字典,列表等,参数传递的方式是引用传递,也就是将可变对象的引用(内存地址)传递给函数,参数会受到影响。
22+
23+
```python
24+
def func(a):
25+
a.append(4)
26+
a.append(5)
27+
# 函数内 a:[1, 2, 3, 4, 5]
28+
print('函数内 a:{}'.format(a))
29+
30+
if __name__ == '__main__':
31+
a = [1, 2, 3]
32+
func(a)
33+
# 函数内 a:[1, 2, 3, 4, 5]
34+
print('函数外 a:{}'.format(a))
35+
```

python_basic/main.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,4 @@
2525
* [python异常处理机制](python异常处理机制.md)
2626
* [\_\_new__()与\_\_init__()方法](new和init方法.md)
2727
* [@property 保护变量的访问与设置](保护变量的访问与设置.md)
28+
* [Python函数参数的传递机制](Python函数参数的传递机制.md)

0 commit comments

Comments
 (0)