Python 2.2a4: Problems with overloading __str__ in subclasses of str
Andreas.Trawoeger
Andreas.Trawoeger at wgkk.sozvers.at
Thu Oct 4 07:10:12 EDT 2001
Hi!
I just ran into a strange problem with Python 2.2a4. I would like to write
a class that behaves like an 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
---
If you wrap the Internet around every person on the planet and spin the
planet, software flows in the network.
- Eben Moglen's Metaphorical Corollary to Faraday's Law
More information about the Python-list
mailing list