标签:
Python的传递究竟是值传递还是引用传递?
在回答这个问题之前,需要知道python中的变量只是一个对象的引用。赋值操作不会改变对象指向的内容,而是把变量从一个对象的引用,改为指向另一个对象的引用。对一个变量重新复制后,复制前后的变量id会发生改变。而在变量直接进行操作情况,分可变对象(list dict...)和不可变对象(int str tuple...)。前者不会改变,而后者则会改变,由于原始的不能改变,只能返回一个新值并赋值给该变量。
In [1]: i = 1 In [2]: id(i) Out[2]: 31122120L In [3]: i = 5 In [4]: id(i) Out[4]: 31122024L In [5]: a = [1,2,3] In [6]: id(a) Out[6]: 62749960L In [7]: a = [23] In [8]: id(a) Out[8]: 62757576L In [9]: i = 5 In [10]: id(i) Out[10]: 31122024L In [11]: i += 1 In [12]: id(i) Out[12]: 31122000L In [13]: id(a) Out[13]: 62757576L In [14]: a.append(5) In [15]: id(a) Out[15]: 62757576L
赋值无法改变函数内或者函数外,变量引用地址的对象。因此python函数是按引用传递,传递的是对象的引用。至于会不会修改这个参数,取决于对变量进行的操作和变量是 可变变量还是不可变变量。
def f(n,x): n = 3 x.append(7) #x = [4,5,6] print "In f()",n,x if __name__ == "__main__": n = 1 x = [0,1,2] print "Before:",n,x f(n,x) print "After:",n,x >>> Before: 1 [0, 1, 2] In f() 3 [0, 1, 2, 7] After: 1 [0, 1, 2, 7] def f(n,x): n += 3 x.append(7) #x = [4,5,6] print "In f()",n,x if __name__ == "__main__": n = 1 x = [0,1,2] print "Before:",n,x f(n,x) print "After:",n,x Before: 1 [0, 1, 2] In f() 4 [0, 1, 2, 7] After: 1 [0, 1, 2, 7] def f(n,x): n = 3 #x.append(7) x = [4,5,6] print "In f()",n,x if __name__ == "__main__": n = 1 x = [0,1,2] print "Before:",n,x f(n,x) print "After:",n,x Before: 1 [0, 1, 2] In f() 3 [4, 5, 6] After: 1 [0, 1, 2]
标签:
原文地址:http://www.cnblogs.com/lbingkuai/p/4576992.html