-1

Why is self.hand an empty list when I call Fred.show_hand() at the end of my code? I am new to OOP and still figuring things out. I look at my code and am happy. It isn't complete but it is simple and is intuitive. I just can't figure out this one thing. My guess is it has something to do with inheritance that I'm not understanding. Please be very descriptive in your answer. I really feel like I'm close to understanding OOP (at least the basics).

import random

class Card():

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

    def show_card(self):
        print(f'{self.value} of {self.suit}')


class Deck():

    def __init__(self):
        self.deck = []
        self.card_values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
        self.card_suits = ['hearts', 'diamonds', 'clubs', 'spades']

    def build_deck(self):
        for value in self.card_values:
            for suit in self.card_suits:
                self.deck.append(Card(value, suit))

    def show(self):
        for card in self.deck:
            Card.show_card(card)

    def shuffle(self):
        random.shuffle(self.deck)

class Player(Deck):

    def __init__(self):
        super().__init__()
        self.hand = []

    def draw(self):
        return self.hand.append(self.deck.pop())

    def show_hand(self):
        print(f'You have {self.hand}')



d = Deck()
d.build_deck()
d.shuffle()
d.show()

fred = Player()
fred.draw()
fred.show_hand()
  • 1
    When I run your example, it ends with `IndexError: pop from empty list` – AGN Gazer Jul 31 '18 at 02:34
  • Inheritance versus Composition: https://stackoverflow.com/questions/20847727/python-inheritance-versus-composition, https://stackoverflow.com/questions/2399544/difference-between-inheritance-and-composition – Stephen Rauch Jul 31 '18 at 02:35

1 Answers1

1

Player uses self.deck in draw method.

At this point (without self.deck.build_deck()) self.deck is empty. I mean self.deck in Player class isn't the same as Deck() which you created before player. You should either build a deck inside draw method or somewhere before it. Or do fred.deck.build_deck() before fred.draw().

Eduard
  • 475
  • 4
  • 14