Constructor problem
Daniel Fackrell
newsgroups.nospam at dfackrell.mailshell.com
Thu Oct 28 18:13:16 EDT 2004
"Nick" <mediocre_person at hotmail.com> wrote in message
news:418169ec$1_1 at alt.athenanews.com...
> I'm writing a simple class to represent a deck of cards. Here is the
> stripped down version. Notice classes Deck and Deck2. Class Deck works,
> Deck2 does not. My thinking is that it should be more efficient (a la
> Deck2) to pre-create the list, and then modify it, rather than appending
I strongly suspect premature optimization here.
> Cards as in Deck.
>
> # --------------------snip--------------
> class Card:
> def __init__(self, rank=0, suit=0):
> self.rank=rank
> self.suit=suit
>
> def __repr__(self):
> r = "A23456789TJQK"[self.rank]
> s = "SHCD"[self.suit]
> return r+s
>
>
> class Deck:
> def __init__(self):
> self.deck = []
> for r in range(13):
> for s in range(4):
> self.deck.append(Card(r,s))
>
> class Deck2:
> def __init__(self):
> self.deck = 52 * [Card()]
This creates a list of 52 references to the card created by Card().
> n = 0
> for r in range(13):
> for s in range(4):
> self.deck[n].rank = r
> self.deck[n].suit = s
> n = n + 1
>
>
> a = Deck()
> print "A --> ", a.deck
> b = Deck2()
> print "B --> ", b.deck
> # ------------snap---------------------
>
> Deck A looks right, 52 cards, one of each. Deck B, on the other hand, is
> 52 of the same card, all rank 12, suit 3.
>
> What am I missing???
>
> Thanks!
> Nick.
How about a list comprehension?
class Deck3:
def __init__(self):
self.deck = [Card(r, s) for s in range(4) for s in range(13)]
More information about the Python-list
mailing list