Sunday, November 23, 2008

Python's object reference

I talk about this subject because the way to stuff arguments in Python is special.Considering following code:
list1=[1,2,3]
str1="hello"
def f2(x,y):
list1.append(4)
y="world"

f2(list1,str1)
list1 #the value is [1,2,3,4],it's changed
str1 # the value is "hello",str1 is not changed

Because Python's argument is the object reference,so if you stuff a mutable object,its value will be change in place.sometime if you want to avoid your outside variable changed by function,you can pass a copy of mutable object to the function:
list1=[1,2,3]
str1="hello"
def f2(x,y):
list1.append(4)
y="world"

f2(list1[:],str1) #Now,we assign a list1[:],it's the copy of list1
list1 #the value is [1,2,3],it's not changed
str1 # the value is "hello",str1 is not changed

Or we can use tuple keyword,convert an array object to a tuple object:
list1=[1,2,3]
str1="hello"
def f2(x,y):
list1.append(4)
y="world"

f2(tuple(list1),str1) #Now,we assign a tuple,it's convert from list1
list1 #the value is [1,2,3],it's not changed
str1 # the value is "hello",str1 is not changed

No comments: