**结论:**python有可变对象和不可变对象之分。如果传入的参数是不可变对象,则在函数体内对形参的修改不会导致实参被修改,而如果传入的是可变对象,实参有可能会变,也有可能不变,这取决于进行改变的操作。
def test(str1):
str1 = "inside"
print("this is function "+str1)
str2 = "outside"
print("this is function "+str2)
test(str2)
print("this is function "+str2) # str2的值并没有被改变
运行结果:
this is function outside
this is function inside
this is function outside
对于其他不可变对象,结果一致。
def test(str1):
str1.append(3)
print("this is function,the value is ",str1)
myStr = [1,2]
print("this is function outside ,the value is ",myStr)
test(myStr)
print("this is function outside ,the value is ",myStr)
运行结果:
this is function outside ,the value is [1, 2]
this is function,the value is [1, 2, 3]
this is function outside ,the value is [1, 2, 3]
python中函数的形参,传入的是实参的引用,实质是指向实参的地址,所以对于形参的操作会改变实参的指。
除了使用python的自带函数,也可通过赋值来修改实参的值:
def test(str1):
for i in range(len(str1)):
str1[i] = i+4
print("this is function,the value is ",str1)
myStr = [1,2]
print("this is function outside ,the value is ",myStr)
test(myStr)
print("this is function outside ,the value is ",myStr)
运行结果:
this is function outside ,the value is [1, 2]
this is function,the value is [4, 5]
this is function outside ,the value is [4, 5]
def test(str1):
str1 = [1,2,3]
print("this is function,the value is ",str1)
myStr = [1,2]
print("this is function outside ,the value is ",myStr)
test(myStr)
print("this is function outside ,the value is ",myStr)
运行结果:
this is function outside ,the value is [1, 2]
this is function,the value is [1, 2, 3]
this is function outside ,the value is [1, 2]
正如上文所说,形参指向的是实参的地址,**当形参被重新赋值时,如果重新赋值后的对象所占的空间大小没有改变,则可以实现对实参的改变。**即对可变对象不改变长度 len(),则可以实现改变。
如果赋值后,形参的长度已经发生了改变,则python会创建一个新的变量,并把变量地址给形参,这时形参和实参不再指向同一个地址了,对形参的修改与实参毫无关系了。
验证如下:
def test(str1):
str1 = [1]
print("this is function,the value is ",str1)
myStr = [1,2]
print("this is function outside ,the value is ",myStr)
test(myStr)
print("this is function outside ,the value is ",myStr)
运行结果:
this is function outside ,the value is [1, 2]
this is function,the value is [1]
this is function outside ,the value is [1, 2]
pyChram 2020.1.3