dkreeft
dkreeft

Reputation: 682

Instantiating child class multiple times based on same parent

Let's say you want to build a deck of 52 playing cards. I have the following Deck class in Python:

class Deck(collections.deque):
    """Creates a deck of 52 playing cards"""
    def __init__(self) -> None:
        super().__init__(
            map(
                Card,
                itertools.product(
                    Suit.__members__.values(), Value.__members__.values()
                ),
            )
        )

As seen, this inherits from collections.deque and relies on three other classes, namely Card, Suit, and Value. This works. However, now I would like to create another class named Decks, that contains k decks, depending on the user input. I just cannot figure out how to instantiate this class properly. What is a Pythonic way of instantiating Decks such that it either contains k Deck objects, or 52 * k Card objects?

edit: Deck contains several methods, such as shuffle() and deal(). I would like to access these methods from Decks, such that I can shuffle all k decks at once or deal one of the 52 * k cards without writing logic to deal with several isolated objects (dealing the 53rd card would need to deal the 1st card from deck 2, etc.).

Upvotes: 0

Views: 99

Answers (1)

Daan Klijn
Daan Klijn

Reputation: 1694

I have simplified your setup a bit, but with this simpler setup the code below should work. Hope it helps!

import collections
import itertools

class Deck(collections.deque):
    """Creates a deck of 52 playing cards"""
    def __init__(self) -> None:
        super().__init__(
                itertools.product(
                    range(13), ['♧','♢','♥','♤']
            )
        )


class Decks(collections.deque):
  def __init__(self, decks):
    deck = Deck()
    for i in range(decks-1):
      deck.extend(Deck())
    super().__init__(
      deck
    )

decks = Decks(3)
print(len(decks))
>> 156

Upvotes: 1

Related Questions