您的位置:首页 > 编程语言 > Python开发

Python中函数参数传递问题

2016-08-30 19:28 323 查看

先上两个例子:

http://python.jobbole.com/85231/

a = 1
def fun(a):
a = 2
fun(a)
print a  # 结果为1

fun(a)中的a,可以看做函数中的形参,可以用任何字符代替:fun(aaa)

a = []
def fun(a):
a.append(1)
fun(a)
print a  # 结果为 [1]

所有的变量都可以理解是内存中一个对象的“引用”,或者,也可以看似c中void*的感觉。

这里记住的是类型是属于对象的,而不是变量。而对象有两种,“可更改”(mutable)与“不可更改”(immutable)对象。在python中,strings, tuples, 和numbers是不可更改的对象,而list,dict等则是可以修改的对象。(这就是这个问题的重点)

当一个引用传递给函数的时候,函数自动复制一份引用,这个函数里的引用和外边的引用没有半毛关系了.所以第一个例子里函数把引用指向了一个不可变对象,当函数返回的时候,外面的引用没半毛感觉.而第二个例子就不一样了,函数内的引用指向的是可变对象,对它的操作就和定位了指针地址一样,在内存里进行修改.

http://blog.csdn.net/crazyhacking/article/details/16114897

 

 

看下面几个例子:

>>> def modifier(number,string,list):
number = 5
string = 'GoodBye'
list = [4,5,6]
print "Inside:", number,string,list

>>> num = 10
>>> string = 'Hello'
>>> list = [1,2,3]
>>> print 'Before:', num, string, list
Before: 10 Hello [1, 2, 3]
>>> modifier(num,string,list)
Inside: 5 GoodBye [4, 5, 6]
>>> print 'After:', num, string, list
After: 10 Hello [1, 2, 3]

 

>>> def modifier(list,dict):
list[0] = 10
dict['a'] = 10
print 'Inside list = %s, dict = %s' %(list,dict)

>>> dict = {'a':1,'b':2,'c':3}
>>> list = [1,2,3,4,5]
>>> print 'Before list = %s, dict = %s' %(list,dict)
Before list = [1, 2, 3, 4, 5], dict = {'a': 1, 'c': 3, 'b': 2}
>>> modifier(list,dict)
Inside list = [10, 2, 3, 4, 5], dict = {'a': 10, 'c': 3, 'b': 2}
>>> print 'After list = %s, dict = %s' %(list,dict)
After list = [10, 2, 3, 4, 5], dict = {'a': 10, 'c': 3, 'b': 2}

 

>>> def swap(list):
temp = list[0]
list[0] = list[1]
list[1] = temp

>>> list = [10,20]
>>> list
[10, 20]
>>> swap(list)
>>> list
[20, 10]

http://blog.chinaunix.net/uid-20937170-id-3275808.html

 

 

 

 

 

 

 

 

 

dd

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: