how can I subclass a string (str)?

Jason R. Coombs jaraco at spamblocker.sandia.gov
Tue Aug 13 18:13:16 CEST 2002


I've been quite enjoying Python 2.2 and the ability to subclass the dict
type.  It's made my code much more elegant.

I'd like to do the same with a string.  I'd like to create a string called
BinaryString which has a couple of representations.  By default, it will
behave exactly as a str and be represented internally as a binary value.  I
would like, however, to assign and retrieve the binary value as a hex string
also.  For example:

BinaryString( '\x33\x22\xAB' ).HexRepr() == '0x3322ab'
and
repr( BinaryString().SetHexRepr( '0x3322AB' ) ) == '\x33\x22\xab'  # 0x
prefix is optional

I could do this by keeping a private attribute in which I store the binary
value, but I believe it would be more elegant to subclass a string.  This
gets more complicated in that strings are immutable, but by the design
described above, the BinaryString would be mutable.

The problem arises in subclassing the type and accessing the internal
representation.

Perhaps my approach to this problem is all wrong.  Are there any suggestions
for creating an elegant solution to the problem described?

Thanks much,
Jason





More information about the Python-list mailing list