0
  • I have 2 classes - Card and Hand
  • Card is with attributes : suit, rank
  • Hand is created by appending empty list by cards. So it`s attributes are cards.

I need to be written in console something like:

Ace D , Queen H

I found in Google that I need to right __str__(self) method carefully. I do not know how in method __str__(self) write stuff that my output would be like I mentioned above. For example :

return self.hand 

does the following :

[<__main__.Card object>, <__main__.Card object>]

I think that Hand object is a list of such kind :

[[card 1],[card 2],..]

which is

[[suit 1,rank 1],[..,..],..]

But I do not know how to take that information from list of list. Such write does not help: hand[i][0] for suit and hand[i][1] for rank of i-th card Still do not get . Here is code:

class Card:
    def __init__(self, suit, rank):
        if (suit in SUITS) and (rank in RANKS):
            self.suit = suit
            self.rank = rank
        else:
            print "Invalid card: ", suit, rank

    def __str__(self):
        return self.suit + self.rank

class Hand:
    def __init__(self):
        self.hand = []
    def __str__(self):
        return str(self.hand)
    def add_card(self, card):
        self.hand.append(card)

Creating OBJECT CARDS

c1 = Card("S", "A")
c2 = Card("C", "2")

Creating OBJECT HAND

test_hand = Hand()

Adding cards to hand

test_hand.add_card(c1)
test_hand.add_card(c2)
print test_hand

result is:

[<__main__.Card object>, <__main__.Card object>]
Cœur
  • 37,241
  • 25
  • 195
  • 267
Ievgenii
  • 477
  • 1
  • 5
  • 13

1 Answers1

1

In the Card() class you could add a __str__() method similar to

    def __str__(self):
        return "{} {}".format(self.rank, self.suit) # assuming Python2.7+

Now when you print a Card instance it will return a user friendly string like Ace D

To print something nice for your hand instance, you could use the .join() string method and a generator inside __str__().

def __str__(self):
    return ', '.join(str(c) for c in self.hand)

Now when you print your hand instance it will give a user friendly output like

Ace D , Queen H

A good resource to learn more about __str__() and __repr__() is this stackoverflow question.

Edit: If you add the recommended __str__() methods to your updated code the output is what you want:

A S, 2 C
Community
  • 1
  • 1
dannymilsom
  • 2,386
  • 1
  • 18
  • 19
  • Thank you! I have one more questions. I am not sure, if I am formulating my question right, please correct me: Is this the only way to gather information about my Class instance(objects c1,c2) from being in the Hand class? And, for example, if I want to do something with Card`s variables in methods of Hand class. – Ievgenii Jun 28 '14 at 16:00