I don't understand how my following code is behaving. I set an instance variable cards_left
to equal an object variable cards_start
on initialisation, but then any time I modify the instance variable it also modifies the class variable.
I found a good few questions similar to this but they're to do with using default values in __init__
arguments. What's I can't understand is why my instance variable value becomes shared with my class variable defined outside __init__
. What's the correct way to avoid this?
class Deck(object):
cards_start = [1, 2, 3, 4]
def __init__(self):
self.cards_left = Deck.cards_start
def change(self):
self.cards_left.pop()
x = Deck()
y = Deck()
x.change()
#all the below will print '[1, 2, 3]'
print('class cards start:', Deck.cards_start)
print('x cards start:', x.cards_start)
print('x cards left:', x.cards_left)
print('y cards start:', y.cards_start)
print('y cards left:', y.cards_left)
EDIT: This question has been marked as a duplicate of this one, but I don't believe it should have been. I'm asking why an instance and class variable have gotten a shared value, whereas that question asks how to create an instance variable.