Python Forum

Full Version: is there a way to automate instatiation of objects?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Suppose I want to create a Card class for standard playing cards like this:

class Card:

    def __init__(self, description, strength):
        self.description = description # e.g. "Two of Clubs"
        self.strength = strength       # e.g. 0 for Twos, 1 for Threes, etc

    def __repr__(self):
        return self.description        # returns "Two of Clubs" rather than the bare object
And then I want to instantiate every Card in a standard deck. Here's the solution I have right now:

card1 = Card("Two of Clubs", 0)
card2 = Card("Two of Spades", 0)
...
card51 = Card("Ace of Hearts", 11)
card52 = Card("Ace of Diamonds", 11)
Is there an automated way to instantiate these objects? And is there an automated way to add them either to a collection representing a standard deck of playing cards, or a Deck class that can be used to instantiate various types of decks (including decks with multiple instances of one card, decks with cards removed, etc.)?
import random

class Card:
    words = ['Two', 'Three', 'Four', 'Five', 'Ace'] # etc
    suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']

    def __init__(self, description, strength):
        self.description = description
        self.strength = strength

    def __repr__(self):
        return self.description

def main():
    deck = []
    for strength, suits in enumerate(Card.suits):
        for w in Card.words:
            deck.append(Card("{0} of {1}".format(w, suits), strength))

    print(deck)
    random.shuffle(deck)
    print(deck)

main()
Oops enumerate wrong value.
import random
 
class Card:
    words = ['Two', 'Three', 'Four', 'Five', 'Ace'] # etc
    suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
 
    def __init__(self, description, strength):
        self.description = description
        self.strength = strength
 
    def __repr__(self):
        return self.description
 
def main():
    deck = []
    for suits in Card.suits:
        for strength, w in enumerate(Card.words):
            deck.append(Card("{0} of {1}".format(w, suits), strength))
 
    print(deck)
    random.shuffle(deck)
    print(deck)