Python 传递参数的方式:值(=对象的引用的值)传递

Python 传递参数的方式为“值传递”,但这种仅仅是对象的引用。
It is “pass by value” but all values are just references to objects.

Python 传递对象的引用的值。
一些数据类型显示的是pass-by-value特征,其他一些和pass-by-reference相似。原因是因为Python中的对象分可变不可变两类。

一些对象,如string, tuplenumber不可变,如果在函数/方法内部修改它们,将会创建新的实例,函数/方法外部的原始实例不会改变。

其他对象,如listdictionary是可变的,因此可以实时改变对象,在函数/方法内部修改对象的同时也会改变外部的原始对象。

下面是两种不同数据类型的例子:

List - 一种可变类型

下面的代码试图修改传递给方法的列表:

def try_to_change_list_contents(the_list):
    print('got', the_list)
    the_list.append('four')
    print('changed to', the_list)

outer_list = ['one', 'two', 'three']

print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)

输出如下:

before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']

然后看一下修改作为参数而传入的引用会发生什么:

def try_to_change_list_reference(the_list):
    print('got', the_list)
    the_list = ['and', 'we', 'can', 'not', 'lie'] #指向新的list,外部list不受影响
    print('set to', the_list)
outer_list = ['we', 'like', 'proper', 'English']
print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)

输出如下:

before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']

在函数内部 the_list现在指向一个新的list,因此无法修改outer_list指向的list。

String - 一种不可变类型

因为是不可变的,所以无法改变string 的内容:
下面的代码试图修改引用:

def try_to_change_string_reference(the_string):
    print('got', the_string)
    the_string = 'In a kingdom by the sea'
    print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)

输出如下:

before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago

不管怎样修改函数内部的string, 外部string不受影响。


[1]https://stackoverflow.com/questions/534375/passing-values-in-python
[2]https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值