Can you use self in __str__

Dave Angel davea at davea.name
Fri Nov 28 03:49:29 CET 2014


On 11/27/2014 08:26 PM, Seymore4Head wrote:
>      def __str__(self):
>          s = "Hand contains "
>          for x in self.hand:
>              s = s + str(x) + " "
>          return s
>
> This is part of a Hand class.  I need a hand for the dealer and a hand
> for the player.
> dealer=Hand()
> player=Hand()

Good so far. But you neglect to tell us Python version.

> This

What's "this" ?  Please include real code, not just vague suggestions.

> prints out 'Hand contains " foo bar
> for both the dealer's hand and the player's hand.
>
> Is there a way to include "self" in the __string__ so it reads
> Dealer hand contains foo bar
> Player hand contains foo bar

You don't show us the __init__ method.  That's where you should 
establish a "name" for the particular instance of Hand.

class Hand(object):
     def __init__(self, name):
         self.name = name
         self.hand =   something ...

     def __str__(self):
           s = self.name + " contains "
           for x in self.hand:
               s = s + str(x) + " "
           return s


When you quote an error, you should be including the whole thing, as 
well as showing the code that triggers it.  In this message you're 
giving us only disjoint fragments, and one line summary of the traceback.

-- 
DaveA



More information about the Python-list mailing list