python函数的传递方式有哪些_python 函数传递方式

在python中方法传递的参数到底是值传递还是引用传递?

1. 首先需要知道python中变量的类型:Python的变量分为可变变量和不可变变量。

针对于不可变的类型比如string int

ContractedBlock.gif

ExpandedBlockStart.gif

1 defchange(str):2 print('str {0} => id is {1}'.format(str,id(str)))3 str = 'goodboy'

4 print('str {0} => id is {1}'.format(str,id(str)))5

6 str = 'someonehan'

7 change(str)8 print('str {0} => id is {1}'.format(str,id(str)))

View Code

上面的代码的输出结果为:

str someonehan => id is 56533104

str goodboy => id is 71791872

str someonehan => id is 56533104

当对str进行重新赋值的时候重新指向了新的内存地址,这个时候外面的变量还指向原来的内存地址,导致打印的结果如上

针对可变的类型如列表

ContractedBlock.gif

ExpandedBlockStart.gif

1 defchange(li):2 print('li {0} => id is {1}'.format(li,id(str)))3 str.append('goodboy')4 print('li {0} => id is {1}'.format(str,id(str)))5

6 str = ['someonehan']7 change(str)8 print('li {0} => id is {1}'.format(str,id(str)))

View Code

上面的代码输出结果为:

li ['someonehan'] => id is 76028360

li ['someonehan', 'goodboy'] => id is 76028360

li ['someonehan', 'goodboy'] => id is 76028360

变量的内存地址没有改变,说明这个修改原来的对象

2. 在将对象传递到python的方法之后调用方法方法对变量做了些什么:函数会自动复制一份引用。在函数内部对此做的修改及改变都是针对这个参数指向的对象做的。

所以传入参数的的方式应该传递的这个参数引用的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值