Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 476
k9b Avatar asked Oct 17 '25 08:10

k9b


2 Answers

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.

like image 147
gsamaras Avatar answered Oct 18 '25 20:10

gsamaras


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)
like image 44
syntonym Avatar answered Oct 18 '25 22:10

syntonym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!