Inheriting the str type

Mike McGavin jester at NOSPAM.mcsnospam.vuw.acNOSPAM.nz
Tue Feb 4 04:23:24 CET 2003


Following up on my query 24 hours ago about CGI and database-friendly 
string manipulation modules, I've been experimenting with writing my 
own. So far I've made a class which acts in a similar way to python's 
str type with a few extras.  I'd like to inherit the python 'str' type 
as a base class, but I've been unsuccessful because of a problem that 
I've encountered.

I need to pass some extra information through the constructor besides 
the value. Python doesn't seem to complain if the constructor of my 
inheriting object is passed one parameter (I haven't tested this 
intensively), but it does complain if there's several.

A reduced example of what I'm trying to do and how it fails is as follows:

=========

Python 2p2.2 (#1, Oct 29 2002, 21:37:49)
[GCC 2.95.3 20010315 (release) (NetBSD nb3)] on netbsd1
Type "help", "copyright", "credits" or "license" for more information.
 >>>
 >>> class zstr(str):
...     def __init__(self, value, arg2=None):
...             str.__init__(self, value)
...             self.__arg2 = arg2
...
 >>> a = zstr("String value", "second argument")
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)
 >>>
 >>> w = zstr("String value",arg2="second argument")
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: 'arg2' is an invalid keyword argument for this function
 >>>

 >>> zstr("String value") ## This works for some reason
'String value'
 >>>

=========

If the second constructor argument is left to the default value as in 
the third example, there isn't any error and all of the zstr constructor 
code seems to be executed. This seems to be true even if the default is 
something other than None.

When the constructor's being called, it *seems* to be acting as if the 
str constructor is being called. On the other hand, type() reports the 
type of a successfully instantiated zstr() (such as the third example 
above) as a zstr object.


Without inheriting I can still make my class act almost the same as 
python's 'str' type, but I'd like to inherit it if possible. Otherwise 
any code that checks that a parameter is a 'str' type breaks, unless 
there's an explicit conversion made back to a python string.


Can anyone suggest a way around this problem?  I'm a bit confused about 
the apparent inconsistencies, but I hope I'm just missing something and 
it's an easy fix.

Thanks for any help.
Mike.





More information about the Python-list mailing list