deriving from str

Nick Coghlan ncoghlan at iinet.net.au
Thu Dec 23 06:43:37 EST 2004


Paolo Veronelli wrote:
> I want to add some methods to str class ,but when I change the __init__ 
> methods I break into problems
> 
> class Uri(str):
>     def __init__(self,*inputs):
>         print inputs
>         if len(inputs)>1:
>             str.__init__(self,'<%s:%s>'%inputs[:2])
>         else:
>             str.__init__(self,inputs[0])
>         print inputs
> a=Uri('ciao','gracco')
> 
> Traceback (most recent call last):
>   File "prova.py", line 9, in ?
>     a=Uri('ciao','gracco')
> TypeError: str() takes at most 1 argument (2 given)
> 
> 
> where is the  str() wrong call.I suppose It's the __new__ method which 
> is wrong or me .Thanks for help

Strings are immutable, so you need to override __new__ rather than __init__.

Py> class Uri(str):
...   def __new__(cls, *inputs):
...     print inputs
...     if len(inputs) > 1:
...       self = str.__new__(cls, '<%s:%s>'% inputs[:2])
...     else:
...       self = str.__new__(cls, inputs[0])
...     return self
...
Py> Uri('ciao', 'gracco')
('ciao', 'gracco')
'<ciao:gracco>'

Note that the first argument is the class object rather than the new instance. 
The __new__ method *creates* the instance, and returns it.

See here for the gory details of overriding immutable types: 
http://www.python.org/doc/newstyle.html

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list