I'm having a problem understanding the following:
class Test():
def __init__(self, data = []):
self.data = data
a = Test()
b = Test()
a.data.append(1)
print(b.data) # prints [1]
class Test1():
def __init__(self, data):
self.data = data
a = Test1([])
b = Test1([])
a.data.append(1)
print(b.data) # prints []
class Test2():
def __init__(self, data = 1):
self.data = data
a = Test2()
b = Test2()
a.data = 2
print(b.data) # prints 1
It prints out [1]
I was expecting that the instance variable data
of b
would be an empty list, because it is a instance variable and not a class variable!
If I do the same thing without a default parameter and just pass an empty list to the parameter data
it works. It also works with an int as a default parameter. I know lists are passed by reference, but that shouldn't be happening anyways.
How? why? Am I not seeing something here??