Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat class method in Python

I would like to repeat a class method several times (26 to be exact) so that I can split a deck of cards to two separate decks. I tried [:26] and [26:] (obviously for lists only) in addition to d1=Deck() then deck1 = d1.deal()*26 and they both did not work. I just learned how to create Classes.

Desired output is deck1=["""26 random cards"""] and deck2=["""26 random cards"""].

Relevant code:

import random
suits = ['H','C','S','D']
ranks = ['A']+list(map(str,range(2,10)))+['X','J','Q','K']
values = [14]+list(range(2,14))

class Card:
    def __init__(self,suit,rank):
        self.suit=suit
        self.rank=rank
        self.value=values[ranks.index(self.rank)]

    def __str__(self):
        return "*------*\n|{0}{1}    |\n|      |\n|    {0}{1}|\n*------*".format(self.rank,self.suit)

    def __gt__(self,other):
        return self.value > other.value

    def __lt__(self,other):
        return self.value < other.value

    def __eq__(self,other):
        return self.value == other.value

class Deck:
    """This class is for creating deck"""
    def __init__(self):
        self.deck=[]
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit,rank))
        self.shuffle()

    def __str__ (self):
        tmp=''
        for card in self.deck:
            tmp+=str(card)+'\n'
        return tmp

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

    def deal(self):
        return self.deck.pop()
like image 855
Ali R. Avatar asked Jul 26 '26 23:07

Ali R.


2 Answers

So the order of operations is going to execute your function once, then repeat the result 26 times. You probably want something more like:

deck1 = [d1.deal() for _ in range(26)]
like image 137
Hoopdady Avatar answered Jul 29 '26 15:07

Hoopdady


Whenever you want to repeat an action a certain number of times, use a for loop.

d2 = []
for i in range(26):
    d2.append(d1.deal())

There's no way for your code at the moment to create an empty deck. Maybe you should have a __init__ that creates an empty deck and then a separate method to make a full deck? Just a thought.

like image 36
Patrick Haugh Avatar answered Jul 29 '26 13:07

Patrick Haugh