python函数可以改变实际参数的值吗_python函数参数改不改变的问题

python函数参数改不改变的问题

**结论:**python有可变对象和不可变对象之分。如果传入的参数是不可变对象,则在函数体内对形参的修改不会导致实参被修改,而如果传入的是可变对象,实参有可能会变,也有可能不变,这取决于进行改变的操作。

不可变对象 : Number,String,Tuple,bool

可变对象 : List,Set,Dictionary

1.不可变对象

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

对于其他不可变对象,结果一致。

2.可变对象的改变操作

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中函数的形参,传入的是实参的引用,实质是指向实参的地址,所以对于形参的操作会改变实参的指。

3.可变对象的赋值改变操作

除了使用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]

4.可变对象的不可变操作

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

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值