Reputation: 127
I am not able to print the cards after calling the get_cards()
method from Deck
class. I am new to Python. I thought by inheriting from the super Deck
class, I would be able to print the cards in the PlayerHand
class.
class Card(object):
RANKS = ["Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"]
SUITS = ["Club", "Diamond", "Hearts", "Spades"]
def __init__(self, rank, suit):
self.suit = suit
self.rank = rank
def __str__(self):
return self.suit + " of " + self.rank
class Deck(object):
def __init__(self):
self.card = []
def populate(self):
for rank in Card.RANKS:
for suite in Card.SUITS:
self.card.append(Card(rank, suit))
def get_cards(self):
return self.card
def shuffle(self):
import random
random.shuffle(self.card)
class PlayerHand(Deck):
def print_cards(self):
cards = self.get_cards()
for card in cards:
print(i)
if __name__=='__main__':
player = PlayerHand()
player.print_cards()
Upvotes: 0
Views: 600
Reputation: 77827
There's nothing to print. You initialized a Hand. This inherits from Deck. Initializing Deck does nothing except to set self.card to the empty list. Thus, when you call print_cards, the hand is still empty.
Nothing in your code invokes any other method. Creating an object does not automatically invoke your other methods. You need to call shuffle and populate explicitly.
Most of all, though, you still have to put cards into the deck from which you're dealing. You have to generate all 52 cards and put them into your master deck.
SIMPLE ADDITION:
class Deck(object):
def __init__(self):
print "Initialize deck"
self.card = []
self.populate()
self.shuffle()
This turns your hand into a full deck of 52 cards, nicely shuffled. If you make the other changes we've all recommended, it even prints out.
Upvotes: 1
Reputation: 876
You forgot to populate the cards after initialize the player. That's player.card is empty and nothing will be printed. You should call player.populate() before calling function print_cards()
As others mentioned, i should be card. And I found a spelling mistake in populate function: 'suit' should be 'suite'
for suite in Card.SUITS:
self.card.append(Card(rank, suit)) # should be suite
Upvotes: 0
Reputation: 1139
Adding to @ScottHunter's answer, i
doesn't mean anything.
In your iteration, you iterate each Card
object in the self.card
member in Deck.
Two problems in your code:
seld.card
in Deck is not initialized. populate
is never called and the cards have no value. You should call this function in the __init__
of Deck.
In your iteration, i
doesn't exist as I said. You should call print with card.rank (to get the value) or card.suit (or both), so it will be something like:
print card # calls the __str__ method of card
Upvotes: 0
Reputation: 49803
Since i
isn't defined anywhere, why would you expect print(i)
to do anything useful?
I think what you want is print(card)
.
Upvotes: 2