Can you use self in __str__

Dave Angel davea at davea.name
Fri Nov 28 06:43:27 EST 2014


On 11/27/2014 08:43 PM, Chris Angelico wrote:
> On Fri, Nov 28, 2014 at 12:26 PM, Seymore4Head
> <Seymore4Head at hotmail.invalid> wrote:
>> dealer=Hand()
>> player=Hand()
>> This 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
>
> No, you can't. You're assuming that the name bound to an object is
> somehow part of that object, but it isn't. What would happen if you
> did this:
>
> print(Hand())
>
> There's no name, so you can't get that information. The only way to do
> it would be to pass that to the Hand object, but you may as well
> simply print it out separately.

It is very useful for a Hand instance to know its "name".

Lots of game strategies treat a collection of such objects identically, 
and then after the fact want to tell them apart.  Printing is one 
example.  But if you've just concluded that object 174fa44 is the 
winner, it'd be nice to be able to tell the user in his own terms.

As you say you shouldn't attempt to guess it, but should pass it into 
the initializer.
-- 
DaveA



More information about the Python-list mailing list