[Python-bugs-list] [ python-Bugs-468061 ] __str__ ignored in str subclass
noreply@sourceforge.net
noreply@sourceforge.net
Wed, 10 Oct 2001 15:52:58 -0700
Bugs item #468061, was opened at 2001-10-04 13:52
You can respond by visiting:
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=468061&group_id=5470
Category: Type/class unification
Group: Python 2.2
Status: Open
Resolution: None
Priority: 5
Submitted By: Tim Peters (tim_one)
Assigned to: Tim Peters (tim_one)
Summary: __str__ ignored in str subclass
Initial Comment:
>From c.l.py; looks messy (e.g., if PyObject_String
didn't ignore octetstring.__str__, the call to str()
in the latter would just recurse forever; and he's
right that b2a_hex requires a genuine string; and e.g.
return b2a_hex(self + "")
would be mighty obscure).
----Original Message-----
From: Andreas.Trawoeger
Sent: Thursday, October 04, 2001 7:10 AM
To: python-list
Subject: Python 2.2a4: Problems with overloading
__str__ in subclasses of str
I would like to write a class that behaves like a
string only with the difference that it displays the
string in hex. In Python 2.2a4 this should be
possible by subclassing str and overloading __repr__
and __str__ :
from binascii import b2a_hex
class octetstring(str):
def __repr__(self):
return b2a_hex(str(self))
def __str__(self):
return b2a_hex(str(self))
o = octetstring('A')
print "o.__repr__():",o.__repr__()
print "o.__str__() :",o.__str__()
print "str(o) :",str(o)
print "o :",o
The result is pretty strange:
o.__repr__(): 41
o.__str__() : 41
str(o) : A
o : A
I'm not shure what's the exact reason for this
problem. Either __str__ isn't used for str() and
print. Or I'm trapped in an chicken egg problem:
I have to convert self to an string (otherwise b2a_hex
won't work) to do this Python should use __str__
(which is the method I'm changing).
cu andreas
----------------------------------------------------------------------
>Comment By: Tim Peters (tim_one)
Date: 2001-10-10 15:52
Message:
Logged In: YES
user_id=31435
The business about b2a_hex not accepting an object of a
subclass of str is now the subject of bug 470040.
----------------------------------------------------------------------
Comment By: Tim Peters (tim_one)
Date: 2001-10-04 13:57
Message:
Logged In: YES
user_id=31435
Looks like I assigned this to Guido by mistake; back to me.
----------------------------------------------------------------------
You can respond by visiting:
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=468061&group_id=5470