str and __setitem__

Peter Otten __peter__ at web.de
Thu Jan 25 05:40:40 EST 2007


Tor Erik Soenvisen wrote:

> What do I need to do to make the code below work as expected:
> 
> class str2(str):
> 
>         def __setitem__(self, i, y):
>                 assert type(y) is str
>                 assert type(i) is int
>                 assert i < len(self)
> 
>                 self = self[:i] + y + self[1+i:]

'self' is a local variable; assigning to it rebinds it but has no effect
outside of the __setitem__() method.
 
> a = str2('123')
> a[1] = '1'
> print a
> 123

> The print statement should return 113

You have to start from scratch as a strings are "immutable" (once created,
their value cannot be changed).

>>> class mutable_str(object):
...     def __init__(self, value):
...             self._value = value
...     def __setitem__(self, index, value):
...             self._value = self._value[:index] + value +
self._value[index+1:]
...     def __str__(self):
...             return self._value
...
>>> a = mutable_str("123")
>>> a[1] = "x"
>>> print a
1x3

Peter



More information about the Python-list mailing list