I have wrote following code in python
class check(object):
def __init__(self):
self.a = [1,2,3,4]
self.b = 5
appending(self.a, self.b)
print "a", self.a
print "b", self.b
def appending(a,b):
a.append(5)
b +=1
If now I run check() function, I got output as following:
a [1,2,3,4,5] [1,2,3,4,5]
b 5 5
So, I have following question
Why it is that list(a) is got updated but not int(b)?
It is related that I am modifying a but i am creating new object when I add 1 in b, in short, it is difference due to immutable or mutable data types.
I have define self.a and self.b in object, i have define a,b in function, then why I can write print a and print b in object, get same output as self.a and self.b
2 Answers 2
self.b is a name for an integer 5. The integer is an immutable object.
When you appear to mutate b you actually create a new object 6 and assign b as a name for it. This in no way affects the object 5 which self.b is a name for.
Comments
Since a is a list, it's passed by reference to the method and any changed done to it within the method, will be done directly to the a.
Variable b is an integer, therefore it's passed by value and a copy of the variable is created to be used within the method. Any change will be visible only within the body of the method, but not to the "outside world".
print "a", ashould beprint "a", self.a, right?self.bstill points to the integer5. When you dob += 1you create a new integer and assign it to the identifierb, but only inside the scope of the functionappending.