trouble subclassing str

John Machin sjmachin at lexicon.net
Thu Jun 23 20:29:37 EDT 2005


Brent wrote:
> I'd like to subclass the built-in str type.  For example:

You'd like to build this weird-looking semi-mutable object as a 
perceived solution to what problem? Perhaps an alternative is a class of 
objects which have a "key" (your current string value) and some data 
attributes? Maybe simply a dict ... adict["some text"] = 100?

> class MyString(str):
> 
>     def __init__(self, txt, data):
>         super(MyString,self).__init__(txt)
>         self.data = data
> 
> if __name__ == '__main__':
> 
>     s1 = MyString("some text", 100)
> 
> 
> but I get the error:
> 
> Traceback (most recent call last):
>   File "MyString.py", line 27, in ?
>     s1 = MyString("some text", 12)
> TypeError: str() takes at most 1 argument (2 given)
> 
> I am using Python 2.3 on OS X.  Ideas?
> 

__init__ is not what you want.

If you had done some basic debugging before posting (like putting a 
print statement in your __init__), you would have found out that it is 
not even being called.

Suggestions:

1. Read the manual section on __new__
2. Read & run the following:

class MyString(str):

     def __new__(cls, txt, data):
         print "MyString.__new__:"
         print "cls is", repr(cls)
         theboss = super(MyString, cls)
         print "theboss:", repr(theboss)
         new_instance = theboss.__new__(cls, txt)
         print "new_instance:", repr(new_instance)
         new_instance.data = data
         return new_instance

if __name__ == '__main__':

     s1 = MyString("some text", 100)
     print "s1:", type(s1), repr(s1)
     print "s1.data:", s1.data

3. Note, *if* you provide an __init__ method, it will be called 
[seemingly redundantly???] after __new__ has returned.

HTH,
John



More information about the Python-list mailing list