These two class definitions are structured identically, except in the weird() class definition the attribute ‘d’ is a list, and in the normal() class definition its an int. I dont understand why the weird() class results in self.d = d, while this is not the case with the class normal(). Why does Python treat int and list differently in this situation?
class weird:
def __init__(self):
d = [1,2,3]
self.d = d
for x in range(3):
d[x] = 10+x
print "d =", d
print "self.d =", self.d
class normal:
def __init__(self):
d = 1
self.d = d
d = 11
print "d =", d
print "self.d =", self.d
And when I run the code, I get
>>> a=weird()
d = [10, 11, 12]
self.d = [10, 11, 12]
>>> b=normal()
d = 11
self.d = 1
You are confusing assignment with mutation of an object.
In one method, you assigned new values to
d, changing what it points to:but in the other method you changed values contained in
d:Note the
[x]there; you are, in essence, telling python to do this:The value of the variable
d, which points to a list, is never changed. The values in the list referred to byd, do change.Take a look at this previous answer of mine, which goes into more detail as to what the difference is between these two statements: Python list doesn't reflect variable change.