Python Forum
is there a way to automate instatiation of objects?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
is there a way to automate instatiation of objects?
#1
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.)?
Reply
#2
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()
99 percent of computer problems exists between chair and keyboard.
Reply
#3
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)
99 percent of computer problems exists between chair and keyboard.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  1. How can I automate this batch creation of documents? 2. How can I automate posting SamLearnsPython 2 3,423 Jul-02-2018, 11:36 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020