[Tutor] MutableString/Class variables

Dave Angel davea at davea.name
Thu May 9 14:42:53 CEST 2013


On 05/09/2013 08:10 AM, Albert-Jan Roskam wrote:
> Hello,
>
> I was just playing a bit with Python and I wanted to make a mutable string, that supports item assignment. Is the way below the way to do this?
> The part I am not sure about is the class variable. Maybe I should also have reimplemented __init__, then call super inside this and add an updated version of "self" so __repr__ and __str__ return that. More general: when should class variables be used? I am reading about Django nd there they are all over the place, yet I have always had the impression their use is not that common.
>

You use a class attribute (not class variable) whenever you want to have 
exactly one such value for the entire program.  If you want to be able 
to manipulate more than one, then you use an instance attribute, 
typically inside the __init__() method.

Your code will fail totally as soon as you try to make a second such 
variable.
     a = MutableStr("01234")
     b = MutableStr("ABCDEFG")

As for how to do it by inheriting from str, I have no idea.  I know that 
inheriting from native types, you generally need to override __new__() 
instead of, or in addition to __init__().  But modifying self the way 
you do in MutableStr isn't going to work the way you expect.  You're 
just modifying a local variable inside the method.  And __setitem__ 
needn't return a value, since nobody's going to look at it.

If I were doing it, I'd have an instance attribute for the string.  But 
I don't know how I could do it without rewriting nearly every str method 
in my class.

>
> # Python 2.7.3 (default, Sep 26 2012, 21:53:58)  [GCC 4.7.2] on linux2
>
> class MutableStr(str):
>      s = None
>      def __repr__(self):
>          return MutableStr.s
>      def __str__(self):
>          return MutableStr.s
>      def __setitem__(self, key, item):
>           print self[:key], item, self[key+1:]
>           self = MutableStr.s = self[:key] + item + self[key+1:]
>            return self
>
> # all results below are as intended
>>>> mstr = MutableStr("01234X678")
>>>> mstr[5] = "&"
> 01234 & 678
>>>> mstr
> 01234&678
>>>> str(mstr)
> '01234&678'
>>>> unicode(mstr)
> u'01234&678'
>


-- 
DaveA


More information about the Tutor mailing list