Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP Deck of Cards in Python [duplicate]

I have been trying to learn object oriented programming in Python, and would like to start by programming card games. I have in mind to try coding several different games, so I wanted to start with a deck class that could be called for whatever game(s) I try to make.

I can get the basic behavior through functions, and I have no idea how to make it into a class. I first came up with this:

class Deck:

    def shuffle():
        cards = []
        suits = ['H', 'D', 'S', 'C']
        for suit in suits:
            for i in range(1, 14):
                cards.append((i, suit))
        shuf_deck = random.sample(cards, len(cards))
        return shuf_deck 

The above works, but it just isn't very good. It's just a function, for one thing, that does two things, creating the deck and shuffling it; it seems these ought to be distinct. It sure seems like creating the deck to start with is a good job for an __init__ function. Based on another question, I got this together:

class Deck:
    def __init__(self):
        self.suits = ['Hearts', 'Diamonds,' 'Spades', 'Clubs']
        self.values = range(1, 14)
        self.cards = []
        for Card in itertools.product(self.suits, self.values):
            self.cards.append(Card)

    def shuffle():
        # Not quite sure what to do here yet
        return self.cards

deck = Deck()
print(deck) 

But this doesn't work. The code within the __init__ function successfully creates the deck, but I can't quite get it 'objectified'. I've tried it several different ways, and it either returns something like <__main__.Deck object at 0x7f56969f5630>, which I believe is the memory address of the object itself, or I get some kind of error, invalid syntax, attribute error, etc. I can't seem to get the data from __init__; when I try to return data directly from __init__ I get an error, and whenever I try to get that data from another method in the class I get errors too. Could someone tell me what I am missing?

like image 510
John Aten Avatar asked Jul 16 '26 09:07

John Aten


1 Answers

deck is the actual Deck object. print(deck) will give you the memory address of the object.

By "get the data from __init__", I believe you are interested in fetching the attributes:

deck.suits # this will give you ['Hearts', 'Diamonds,' 'Spades', 'Clubs']
deck.values # this will be [1,2, ..13]

and so on.

like image 87
jh314 Avatar answered Jul 18 '26 00:07

jh314