python 函数传递方式

在python中方法传递的参数到底是值传递还是引用传递?

1. 首先需要知道python中变量的类型:Python的变量分为可变变量和不可变变量。

    针对于不可变的类型比如string int

1 def change(str):
2     print('str {0} => id is {1}'.format(str,id(str)))
3     str = 'goodboy'
4     print('str {0} => id is {1}'.format(str,id(str)))
5 
6 str = 'someonehan'
7 change(str)
8 print('str {0} => id is {1}'.format(str,id(str)))
View Code

上面的代码的输出结果为:

str someonehan => id is 56533104
str goodboy => id is 71791872
str someonehan => id is 56533104

当对str进行重新赋值的时候重新指向了新的内存地址,这个时候外面的变量还指向原来的内存地址,导致打印的结果如上

    针对可变的类型如列表

1 def change(li):
2     print('li {0} => id is {1}'.format(li,id(str)))
3     str.append('goodboy')
4     print('li {0} => id is {1}'.format(str,id(str)))
5 
6 str = ['someonehan']
7 change(str)
8 print('li {0} => id is {1}'.format(str,id(str)))
View Code

上面的代码输出结果为:

li ['someonehan'] => id is 76028360
li ['someonehan', 'goodboy'] => id is 76028360
li ['someonehan', 'goodboy'] => id is 76028360

变量的内存地址没有改变,说明这个修改原来的对象

2. 在将对象传递到python的方法之后调用方法方法对变量做了些什么:函数会自动复制一份引用。在函数内部对此做的修改及改变都是针对这个参数指向的对象做的。

    所以传入参数的的方式应该传递的这个参数引用的对象。

posted @ 2016-12-21 22:22  someOneHan  阅读(456)  评论(0编辑  收藏  举报