1

Firstly I am a beginner in python and this is where I got struck

Here class card returns a string

When I print the list itself without giving an index it shows me a garbage value, but when I give an index it shows me the value that I want. I don't know why this is happening.

class Card:

    def __init__(self,suit,rank):
        self.suit=suit
        self.rank=rank


    def __str__(self):
        return f'{self.rank} of {self.suit}'


allcards=[]
allcards.append(Card('Spades','Jack'))

print(allcards)

Output: [<__main__.Card object at 0x0000013B5E72EFD0>]

class Card:

    def __init__(self,suit,rank):
        self.suit=suit
        self.rank=rank


    def __str__(self):
        return f'{self.rank} of {self.suit}'

allcards=[]
allcards.append(Card('Spades','Jack'))

print(allcards[0])

Output: Jack of Spades

I want to print the list by using the first case how can I?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 4
    Because when you print a list it prints the `__repr__`s of its contents, not their `__str__`s. – jonrsharpe Jul 30 '21 at 16:41
  • Use `print(*allcards)` – Barmar Jul 30 '21 at 16:42
  • Thanks for your valuable suggestions. – Vamshi Krishna Reddy Jul 30 '21 at 16:52
  • its not working here vscode says **Unpack operation not allowed in this context** @Barmar `print(f'{player_one.name} cards : {*player_one.allcards}')` – Vamshi Krishna Reddy Jul 30 '21 at 17:09
  • Ok I got it to avoid this use `def __repr__ ()`instead of `def __str__()` when returning a string in a class to print list without giving an index – Vamshi Krishna Reddy Jul 30 '21 at 17:17
  • @VamshiKrishnaReddy That's not what I said to do. I said `print(*allcards)` instead of `print(allcards)` – Barmar Jul 30 '21 at 18:29
  • @Barmar yes, I agree but implementing my code using the same principle doesn't work, here I posted the code which is a shorter version of my code but the problem is the same. Playerone is an instance of the Player class in that I initialized allcards list, modified it using some other functions so i need to print allcards using player one instance ie `playerone.allcards` it's showing me the first case output but I need to find out the way to get the second case output – Vamshi Krishna Reddy Jul 31 '21 at 04:31
  • without replacing `__repr__` with `__str__` is there any way to do it? – Vamshi Krishna Reddy Jul 31 '21 at 04:44
  • You could create a `Deck` class and define its `__str__` method, instead of using an ordinary list. Or you could define a `printCards()` function that prints a list of cards the way you want. – Barmar Jul 31 '21 at 06:16

0 Answers0