python 中不可变对象有 int,string,float,tuple
python 中可变对象有 dict,list
示例如下,
def try_to_change_string_reference(the_string , *args):
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
the_string 是外部传进的一个值,是在 try_to_change_string_reference 方法内部分配一个新的字符串,对外部的outer_string不产生影响。
可变参数list ,修改这个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']
改变这个list的引用
def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
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']
outer_list 作为值传入到方法内,在方法内重新分配一个list ,所以值改变了。