Arkeor
Arkeor

Reputation: 51

empty list as default value: same allocation in memory

I want to initialize several instances of the same class with an initial empty list attribute, in which I want to add elements later in the script.

But I met a problem: the empty lists had the same allocation in memory.

For example, if I create this class with two instances:

class FirstClass: 
    def __init__(self, values=[]):
        self.values = values

a = FirstClass()
b = FirstClass()

If I want to add a value in b.values:

b.values += ['boat']
print(a.values) # ['boat']

# Also :

print(a.values is b.values) # True

It turns out that this solves my problem:

class SecondClass:
    def __init__(self, values=None):
        self.values = values if values is not None else []

A = SecondClass()
B = SecondClass()

print(A.values is B.values) # False

I don't understand the difference at all, I consider myself lucky to have found this...

Is there a reason for the FirstClass not behaving like the SecondClass ?

Upvotes: 0

Views: 26

Answers (0)

Related Questions