码迷,mamicode.com
首页 > 编程语言 > 详细

python 函数传递方式

时间:2016-12-21 23:43:58      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:nbsp   one   类型   splay   针对   自动   修改   bsp   lin   

在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的方法之后调用方法方法对变量做了些什么:函数会自动复制一份引用。在函数内部对此做的修改及改变都是针对这个参数指向的对象做的。

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

python 函数传递方式

标签:nbsp   one   类型   splay   针对   自动   修改   bsp   lin   

原文地址:http://www.cnblogs.com/someoneHan/p/6208778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!