def foo(bar):
print "inside {} with id {}".format(bar, id(bar))
bar = "bar"
print "outside {} with id {}".format(bar, id(bar))
foo(bar)
baz = [1,2]
print "outside {} with id {}".format(baz, id(baz))
foo(baz)
返回结果
outside bar with id 4334173920
inside bar with id 4334173920
outside [1, 2] with id 4333883616
inside [1, 2] with id 4333883616
显然python传参数的方式是传引用。
不可变对象
对于不可变对象,你在函数内做什么都不会改变外面的结果
def foo(bar):
print "inside {} with id {}".format(bar, id(bar))
bar = "baz"
print "inside {} with id {}".format(bar, id(bar))
bar = "bar"
print "outside {} with id {}".format(bar, id(bar))
foo(bar)
print "outside {} with id {}".format(bar, id(bar))
返回结果
outside bar with id 4472704736
inside bar with id 4472704736
inside baz with id 4472704776
outside bar with id 4472704736
我们可以很明显的看到,在执行bar = "baz"之后,bar就指向了另一个字符串对象了,而在函数外面,什么都没有改变。
可变对象
对于可变对象,你可以在内部改变它,这种改变会反馈到外面。
def foo(bar):
print "inside {} with id {}".format(bar, id(bar))
bar.append(3)
print "inside {} with id {}".format(bar, id(bar))
bar = [1,2]
print "outside {} with id {}".format(bar, id(bar))
foo(bar)
print "outside {} with id {}".format(bar, id(bar))
返回结果
outside [1, 2] with id 4358607072
inside [1, 2] with id 4358607072
inside [1, 2, 3] with id 4358607072
outside [1, 2, 3] with id 4358607072
我们在内部改变了bar这个list(可变对象),它的引用没有改变。
但是如果你在函数中修改了引用,那你在函数中做任何操作都不会影响到外面。
def foo(bar):
print "inside {} with id {}".format(bar, id(bar))
bar = [1,2,3]
print "inside {} with id {}".format(bar, id(bar))
bar = [1,2]
print "outside {} with id {}".format(bar, id(bar))
foo(bar)
print "outside {} with id {}".format(bar, id(bar))
结果
outside [1, 2] with id 4544712928
inside [1, 2] with id 4544712928
inside [1, 2, 3] with id 4544951360
outside [1, 2] with id 4544712928
我们在函数中改变了变量bar指向的引用,它就不再指向外面那个list了,而是指向了一个新创建的list。对这个新list进行任何操作都不会影响外面的那个list