[Tutor] help with __str__

Ron A rha207 at yahoo.com
Thu Sep 2 23:45:56 CEST 2004


This is from the book "Python Programming for the
absolute beginner"
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.

Ron A

# Playing Cards
# Demonstrates combining objects
# Michael Dawson - 4/9/03

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


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) + "  "
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
        other_hand.add(card)


# main
card1 = Card(rank = "A", suit = "c")
card2 = Card(rank = "2", suit = "c")
card3 = Card(rank = "3", suit = "c")
card4 = Card(rank = "4", suit = "c")
card5 = Card(rank = "5", suit = "c")


my_hand = Hand()
my_hand.add(card1)
my_hand.add(card2)
my_hand.add(card3)
my_hand.add(card4)
my_hand.add(card5)
print "\nPrinting my hand after adding 5 cards:"
print my_hand

your_hand = Hand()
my_hand.give(card1, your_hand)
my_hand.give(card2, your_hand)
print "\nGave the first two cards from my hand to your
hand."
print "Your hand:"
print your_hand
print "My hand:"
print my_hand

my_hand.clear()
print "\nMy hand after clearing it:"
print my_hand

raw_input("\n\nPress the enter key to exit.")




__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Tutor mailing list