Python Parameter Passing Note
我刚刚开始学习Python, Python中的参数传递总是让我很困惑。我写了4个简单的Demo,帮助我理解Python的参数传递,希望对大家都能有所帮助。
0:
def change(x): x = 1
a = 10
print('a is {0}'.format(a)) change(a) print('a is {0}'.format(a))
Output:
a is 10
a is 10
1:
def change1(x): x = [1, 2] a = [10, 20]
print('a is {0}'.format(a)) change1(a) print('a is {0}'.format(a))
Output:
a is [10, 20]
a is [10, 20]
2: [NOTE]We should pay more attention to this demo.
def change2(x): x[:] = [1, 2, 4] a = [10, 20]
print('a is {0}'.format(a)) change2(a) print('a is {0}'.format(a))
Output:
a is [10, 20]
a is [1, 2, 4]
3:
def change3(x): x[0] = [1, 2, 4] a = [10, 20]
print('a is {0}'.format(a)) change3(a) print('a is {0}'.format(a))
Output:
a is [10 20]
a is [[1, 2, 4], 20]]
对于参数传递,我总是用传值或者传址来理解,但在《Python基础教程》中建议我们用这样的方法来理解Python中的参数传递:(以Demo1为例说明)
1.#demo1 again: 2.def change1(x): 3. x = [1, 2] 4.
5.a = [10, 20]
6.print('a is {0}'.format(a)) 7.change1(a) 8.print('a is {0}'.format(a)) #We can think it in the following way: #5行: a = [10, 20]
#7行:NOTE,用下面代码来理解参数传递 x = a
#3行: x = [1, 2]
通过这样方法来理解参数传递,省去了我们的很多的考虑,个人感觉这种方法还是很不错的,不知道各位大神们是怎么理解Python中的参数传递的?