File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ ```
Original file line number Diff line number Diff line change 2525* [ python异常处理机制] ( python异常处理机制.md )
2626* [ \_\_ new__ ()与\_\_ init__ ()方法] ( new和init方法.md )
2727* [ @property 保护变量的访问与设置] ( 保护变量的访问与设置.md )
28+ * [ Python函数参数的传递机制] ( Python函数参数的传递机制.md )
You can’t perform that action at this time.
0 commit comments