Can you use self in __str__
steve+comp.lang.python at pearwood.info
Fri Nov 28 09:25:54 CET 2014
> 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.
> 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
Not unless you tell the instance what name you want it to use.
Instances (objects) have no way of knowing the name of the variable you
attach them to. Or even if there is such a variable -- there could be one,
or none, or a thousand.
# one variable, one instance
dealer = Hand()
# three variables, one instance
player1 = player2 = player3 = Hand()
# make that four variables
player4 = player2
# no variable, one instance
some_list = [1, 2, 3, Hand(), 5]
If you ask each instance what their name is, how would they know?
The only way is to give them a name when you create them:
def __init__(self, name):
self.name = name
dealer = Hand("dealer")
player1 = Hand("Bert")
player2 = Hand("Ernie")
player3 = Hand("Scarface")
Now the instances know what their name is, since you've told them, and can
use them any way you like:
template = "%s's hand contains: "
return (template % self.name) + "King of Spades"
More information about the Python-list