I'm trying to use str to create a string representation of my object and use is when printing another object that uses this object. My implementation isn't working though.
I saw this: How to properly define a return string within a for loop for a Class using OOP in Python and thought I had everything correct, but I'm still not getting what I want in the output
Here is my code:
class Card:
def __init__(self, name):
self.name = name
def __str__(self):
print("using Card.__str__()")
return self.name
class Deck:
def __init__(self):
self.deck = []
def add_cards(self, cds):
self.deck.append(cds)
def __str__(self):
print("using Deck.__str__()")
temp = ""
for i in range(len(self.deck)): # <- iterating over list of Card objs
temp += str(self.deck[i]) # <- deck[i] is Card obj, why doesn't this use Card.__str__()?
if i < len(self.deck)-1:
temp += ", "
return temp
card1 = Card("Apples")
card2 = Card("Peaches")
card3 = Card("Grapes")
card4 = Card("Pears")
cards = [card1, card2, card3, card4]
deck = Deck()
deck.add_cards(cards)
print(deck)
I'm expecting to see:
Apples, Peaches, Grapes, Pears
But instead I'm getting:
using deck.str()
[<main.Card object at 0x7f7f1d1103a0>, <main.Card object at 0x7f7f1d146520>, <main.Card object at 0x7f7f1d1
46be0>, <main.Card object at 0x7f7f1d146dc0>]
What am I doing wrong???