Can you use self in __str__

Dave Angel davea at
Fri Nov 28 10:37:36 CET 2014

On 11/27/2014 10:31 PM, Seymore4Head wrote:
> On Thu, 27 Nov 2014 21:49:29 -0500, Dave Angel <davea at>
> wrote:
> class Hand:
>      def __init__(self):
>          self.hand = []
>          # create Hand object
>      def __str__(self):
>          s = 'Hand contains '
>          for x in self.hand:
>              s = s + str(x) + " "
>          return s
> I am using 2.7 (Codeskulptor).  This is working code.  It starts with
> an empty list that gets appended from a full deck of shuffled cards.
> dealer=Hand()
> player=Hand()
> I don't really know how to post working code without posting a lot.  I
> am not being too successful in trying to post enough code to have it
> work without posting the entire code.
> Here is the link if you want to run it.
> The print out looks like this:
> Hand contains H4 DQ.
> I can (and am) currently printing the hand like this:
> print "Player's",player
> print "Dealer's",dealer
> My question is can you add (self) in the __str__ so when you issue the
> command "print player" the "player" part is included in the __str__.

You've already got self in the __str__ method, or you wouldn't have 
access to self.hand.  But there's no characteristic of 'self' that has 
any idea of a name like "dealer" or "player".  You have to add that if 
you want it, as I suggested in my first guess.  Steven has shown you as 
well, along with a better explanation.

An object does NOT know the name or names that may be bound to it, any 
more than I know what page of the county register has my birth 
certificate recorded.  If I want to know my own name, I'd better 
remember it.  Along with any nicknames I want to respond to.  The way to 
do it is the same way to know the hand that I hold, make an instance 
attribute.  And the place to do that is in the __init__() method.

class Hand:
     def __init__(self, myname):
         self.hand = []
         # create Hand object = myname

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



More information about the Python-list mailing list