Can you use self in __str__

Seymore4Head Seymore4Head at Hotmail.invalid
Thu Nov 27 22:35:16 EST 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.
>> 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
>
>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
>this:
>
>#!/usr/bin/env python
>
>class Hand(object):
>def __init__(self):
>self.hand = [1, 2, 3, 4]
>
>def __str__(self):
>s = self._myname + " hand contains "
>for x in self.hand:
>s = s + str(x) + " "
>return s
>
>@property
>def _myname(self):
># get the module
>mod = self.__module__
>import sys
>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):
>break
>else:
>#nothing found
>return ""
>return name
>
>John = Hand()
>print(John)
>
># this prints
># John hand contains 1 2 3 4
>
>bad indentation with my wasavi plugin, see paste:
>
>https://bpaste.net/show/f5b86957295f
>
>
>What if it's in the local namespace of a function or method? IDK, try
>to get that thing first.
>
>
>Regards



More information about the Python-list mailing list