Ali R. Ali R. - 1 month ago 16
Python Question

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()

Answer

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)]