k9b
k9b

Reputation: 1493

Python object keeping data from previous?

I've seen multiple instances of this question like this one, but it fails to identify what exactly I am doing wrong since I don't have default arguments.

What am I doing wrong? Python object instantiation keeping data from previous instantiation?

#Table.py
class Table:

def __init__(self, players):
    self.deck = Deck()

And this is Main

t = Table(2)
print len(t.deck.cards)

t = Table(2)
print len(t.deck.cards)

I would expect this to print 48 each time, but instead it prints

48 and then 96

Why is this? Shouldn't this member variable be overridden every time?

#Deck.py
from Card import *
import random

class Deck:

suits = ['H','C','D','S']
numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14]
cards = []

def __init__(self):
    for num in self.numbers:
        for suit in self.suits:
            c = Card(num,suit)
            self.cards.append(c);
    random.shuffle(self.cards)

Card.py

class Card:

def __init__(self, num, suit):
    self.num = num
    self.suit = suit

def __repr__(self):
    return str(self.num) + str(self.suit)

def __str__(self):
    return str(self.num) + str(self.suit)

Upvotes: 4

Views: 1641

Answers (3)

gsamaras
gsamaras

Reputation: 73366

Initialize cards in the constructor, like this:

def __init__(self):
    self.cards = []
    for num in self.numbers:
        for suit in self.suits:
            c = Card(num,suit)
            self.cards.append(c);
    random.shuffle(self.cards)

That way, every time a new instance of the class is created, cards will be freshly initialized.

Your approach didn't work as you wished, since cards is a class data member, shared among all instances of class Deck.

Upvotes: 6

syntonym
syntonym

Reputation: 7384

suits, numbers and cards are class variables. So when doing self.cards.append(c) you add to a class variable, which is shared by all instances of all Deck instances.

Put them into __init__ instead:

def __init__(self):

    self.cards = []
    for num in self.numbers:
        for suit in self.suits:
            c = Card(num,suit)
            self.cards.append(c);
    random.shuffle(self.cards)

Upvotes: 2

Basya
Basya

Reputation: 1485

You are using class variables instead of instance variables. See, for example, python class variables

So even though you instantiate a new instance, you don't get a new instance of the static class variables.

Suits, numbers, cards. If you want instance variables, use "self.", and do it in the init function.

You are appending cards each time you instantiate, but you are appending them to the class variable. Thus you end up with twice as many.

Upvotes: -1

Related Questions