Reputation: 89
I've tried diffrent methods to print a list from a class by looping it or changing it for a string. When I change it within a class for a string I get multiple "<__main__.Card object at 0x00000262D8279820>"
and when I'm looping it within a class I get Traceback "TypeError: __str__ returned non-string (type Card)"
. How can I simply display a list from a class?
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = values[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
Upvotes: 1
Views: 863
Reputation: 39354
I don't know what a Card
is, but you can just return the string of the deck:
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit, rank))
def __str__(self):
return str(self.deck)
You may need to also implement __repr__()
to get lists to render your cards:
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return self.rank + ' of ' + self.suit
def __repr__(self):
return self.__str__()
Upvotes: 0
Reputation: 477
From what I gather you are trying to print the contents of a list. But it looks like the list contains cards of the class Card
. It is also an object and will return something like "<main.Card object at 0x00000262D8279820>". It seems like you will need __str__
for the Card
class too.
Also using return
will only return the first element as it will exit the block.
Upvotes: 0
Reputation: 517
You actually never transformed your card to a string in your given example. Here's a way to do it.
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit, rank))
def __str__(self):
return ', '.join(map(str, self.deck))
map(str, self.deck)
will transform every element of self.deck
to a string using their __str__
method.', '.join(...)
will concatenate every element of the list, separating they with ', '
.This will work assuming your Card
class defines a __str__
method, for instance :
class Card:
[...]
def __str__(self):
return f"{self.suite}: {self.rank}"
Upvotes: 1