1

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.

Community
  • 1
  • 1
Mark M
  • 455
  • 2
  • 17
  • You probably want to set `self.cards_left` to a *copy* of `cards_start`. otherwise it seems all instances are sharing the *same* list object. – gen_Eric May 02 '17 at 20:06
  • I get that they're sharing the same list, but I don't understand why. And how do I set `self.cards_left` to a copy of `cards_start` – Mark M May 02 '17 at 20:12
  • In this case, `self.cards_left = Deck.cards_start.copy()` would suffice. Would be more complicated if `cards_start` contained any other lists/dicts/tuples/other container types. For that, research deep copies. – glibdud May 02 '17 at 20:49
  • (In Python 2 or early versions of 3.x, you may need to do `Deck.cards_start[:]` instead of `Deck.cards_start.copy()`.) – glibdud May 02 '17 at 20:55
  • Thanks fro the help guys. It's the way values can become shared in python that was confusing me. I think I'm starting to get my head around it now. – Mark M May 03 '17 at 18:12

0 Answers0