廣告

2015年3月7日 星期六

[python]Passing by reference or value| mutable type &immutable type




variable asign in python is  just a reference,
and all data is object.

但是又分為mutable type (list) & immutable type (String)

Function:
  mutable type  :reference
  immutable type:value


範例如下:




print 'List (mutable type)'
def ange_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
ange_list_reference(outer_list)
print 'after, outer_list =', outer_list

print '==================================='


print 'String(immutable type)'

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


print 'Int (immutable type)'

def change_int(the_int):
    print 'got', the_int
    the_int = '9'
    print 'set to ',the_int

outer_int  = 1

print 'before ,outer_int=',outer_int
change_int(outer_int)
print'after ,outer_int=' ,outer_int



print 'asign operation is use reference not copy'
print 'example:'
L = [1,2,3]
M = ['X' ,L, 'Y']
print M
print 'set L[0]=9'
L[0]=9
print M
print 'the content of M will be set too'


print'============='
print 'if dont want set M, you need use copy'
L = [1,2,3]
M = ['X',L[:],'Y']
print M
print 'set L[0]=9'
L[0] = 9
print M
print 'the content of M wont be set '

consol
===================================
String(immutable type)
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
Int (immutable type)
before ,outer_int= 1
got 1
set to  9
after ,outer_int= 1


asign operation is use reference not copy
example:
['X', [1, 2, 3], 'Y']
set L[0]=9
['X', [9, 2, 3], 'Y']
the content of M will be set too
=============
if dont want set M, you need use copy
['X', [1, 2, 3], 'Y']
set L[0]=9
['X', [1, 2, 3], 'Y']
the content of M wont be set

沒有留言:

張貼留言