I have the following problem which I would like to illustrate by showing the following two minimal classes first before I explain in detail:
class Example1:
def __init__(self):
pass
def function11(self,x):
x=2*x+1
return x
def function12(self,x):
y=0
z=x
while y<z:
x=self.function11(x)
y=y+1
return x
class Example2:# the only difference to the previous class: it handles
#lists instead of numbers
def __init__(self):
pass
def function21(self,x):
x[0]=2*x[0]+1
return x
def function22(self,x):
y=0
z=x[0]
while y<z:
x=self.function21(x)
y=y+1
return x
if __name__=="__main__":
A1=Example1()
x1=A1.function11(3)
y1=A1.function12(x1)
print'Result of Example1:'
print x1
print y1
print
A2=Example2()
x2=A2.function21([3])
y2=A2.function22(x2)
print'Result of Example2:'
print x2
print y2
And here is the output:
Result of Example1:
7
1023
Result of Example2:
[1023]
[1023]
>>>
What I don't understand here: why is the variable x2 overwritten with the value of y2? It obviously depends on the fact that lists are mutable objects in Python, am I right? My search on this led me to an article by Effbot. Still, I don't really understand what's going on here.