Can you use self in __str__
Seymore4Head at Hotmail.invalid
Fri Nov 28 04:35:16 CET 2014
On Fri, 28 Nov 2014 11:04:26 +0800, Shiyao Ma <i at introo.me> wrote:
>2014-11-28 9:26 GMT+08:00 Seymore4Head <Seymore4Head at hotmail.invalid>:
>> 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
>I bet you want the object name (aka, dealer, player) be included in
>the string 's'.
That is exactly what I want, but your explanation is too complicated
for my feeble mind to get just yet.
>To that end, you need to access the namespace where 'self' is in.
>But I dunno where the namespace 'self' resides in.
>Does PyObject has a field to store the namespace of an object?
>Appreciated if anyone could
>inform me on this.
>Now, make a little assumption that the instance lives in the module
>level. Then we can do
>self.hand = [1, 2, 3, 4]
>s = self._myname + " hand contains "
>for x in self.hand:
>s = s + str(x) + " "
># get the module
>mod = self.__module__
>ns = vars(sys.modules[mod])
># NB only works the instance is at the module level
>for name, obj in ns.iteritems():
>if id(obj) == id(self):
>John = Hand()
># this prints
># John hand contains 1 2 3 4
>bad indentation with my wasavi plugin, see paste:
>What if it's in the local namespace of a function or method? IDK, try
>to get that thing first.
More information about the Python-list