I was confused due to the difference between class and instance variables. I read this post How to avoid having class data shared among instances? which did a good job at explaining things, however there is still something I found interesting which is not explained in that post.
Consider the following code:
class Person():
def __init__(self, givenList=[]):
self.list1 = []
self.list2 = givenList
personA = Person()
personB = Person()
personA.list1.append([1, 2])
personB.list1.append([3, 4])
personA.list2.append([5, 6])
personB.list2.append([7, 8])
print(personA.list1) # prints [[1, 2]]
print(personB.list1) # prints [[3, 4]]
print(personA.list2) # prints [[5, 6], [7, 8]], but I expected [[5, 6]]
print(personB.list2) # prints [[5, 6], [7, 8]], but I expected [[7, 8]]
print(personA.list1 == personB.list1) # prints False
print(personA.list2 == personB.list2) # prints True, but I expected False
Aren't both list1
and list2
instance variables? I understand that if I would type list3 = [9, 10]
before __init__()
it would be shared among personA
and personB
. However, it is surprising to me that list2
in my example is also shared among personA
and personB
.