I have been trying for about a week now to make this work. My goal is to take the list of cards and append list item 0, 1, and 2 to the user_hand list. When ever I run the code I get things such as <main.Card object at 0x0000021DA02924D0> printed instead of A♥. What am I doing incorrectly to produce such an error? This is my first time working with python Classes, so I could be tripping up there.
import random
user_hand = []
class Card():
def __init__(self, name, suit):
self.name = name
self.suit = suit
def print_card(self):
suits = {"H":"♥","D":"♦","C":"♣","S":"♠"}
print(f"{self.name}{suits[self.suit]}")
class Carddeck():
def __init__(self):
self.cards = []
names = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A")
suits = ("H", "D", "C", "S")
for suit in suits:
for name in names:
card = Card(name, suit)
self.cards.append(card)
def cupid(self):
random.shuffle(self.cards)
def dealing(self):
user_hand.append(self.cards[0])
user_hand.append(self.cards[1])
user_hand.append(self.cards[2])
card = Card("A", "H")
card.print_card()
deck = Carddeck() # creates the deck.
deck.cupid() # shuffles the deck
deck.dealing() # deals to player, but this gives the strange output
for card in deck.cards:
card.print_card()
print(user_hand)
When python tries to print the list, it prints the representation of each of the objects. You can customize this behavior by using
__repr__. You already have aprint_cardmethod, so you can just modify this. Then, to print the card, it's simplyprint(my_card).