Inheriting the str type

Mike McGavin jester at NOSPAM.mcsnospam.vuw.acNOSPAM.nz
Tue Feb 4 01:58:38 EST 2003


Thanks for the help, Andrew.

Andrew Bennetts wrote:

[--snip--]

> In theory, Pythonic code won't care if something is a string, but simply if
> it behaves more-or-less like a string.  Inheritance isn't necessarily the
> right way for a class to say "I implement this behaviour".

It wasn't python itself as much as the specific way code is written with 
it from time to time.  For example, trying to run 
binascii.b2a_hex(zstr("Hello")) on my pseudo-string class raised a 
TypeError.  I haven't gone into the source to check, but presumably it 
starts with something like:

   if not isinstance(incomingobj, str):
     raise TypeError("String needed...")

It was effectively blocking anything that wasn't a string from being 
processed.

If there's a way to fool python into thinking that my zstr() is a 
standard python string when it's not, that'd be another idea to look at. 
  Hopefully though I have the inheritance thing sussed now thanks to 
yours and Mikes pointers for using the __new__() constructor instead of 
__init__(), which I appreciate. It seems to be working smoothly.

Thanks.
Mike.





More information about the Python-list mailing list