[Tutor] help with __str__

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Sep 3 00:39:23 CEST 2004

> slightly modified. It's concantenating rank and suit
> each time you create a new card and it seems to be
> doing it without having to use print card each
> time. How is the str method being used without using
> print? I'm really getting confused now.

What makes you think its concatenating anything?

The only time they get concatenated is when they get printed
which is when the __str__ gets called. And it only concatenates
for the duration of the print.

What makes you think its doing anything else?

> class Card(object):
>     """ A playing card. """
>     def __init__(self, rank, suit):
>         self.rank = rank
>         self.suit = suit
>     def __str__(self):
>         rep = self.rank + self.suit
>         return rep

Actually this is a pretty dumb class, a tuple would work just as well!

> class Hand(object):
>     """ A hand of playing cards. """
>     def __init__(self):
>         self.cards = []
>     def __str__(self):
>         if self.cards:
>            rep = ""
>            for card in self.cards:
>                rep += str(card) + "  "

Note that the call to str() here will also call the __str__ method
of each card. But that only applies when printing a hand. The
concatenation is still only temporary.

>         else:
>             rep = "<empty>"
>         return rep
> print my_hand

So within this call the individual card __str__() methods get called.


Alan G.

More information about the Tutor mailing list