I append all possible cards in self.deck
list but when I tried to print out the list with string representation method it gave me <__main__.Deck object at 0x00238148>
I don't know why! My code is below and I would really appreciate if anyone could look at it and just tell me how to get all card
in class Deck
?
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
class Card():
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return self.rank + " of " + self.suit
class Deck():
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit, rank))
def __str__(self):
for card in self.deck:
return card
deck = Deck()
print(deck)
The __str__
method should always return string. Here in your card class the return type of __str__
is correct but in the Deck class you are returning the card object rather you should call the string representation of the card object inside __str__
method.
class Deck():
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit, rank))
def __str__(self):
for card in self.deck:
return str(card)