[Tutor] MutableString/Class variables

Albert-Jan Roskam fomcl at yahoo.com
Thu May 9 14:10:41 CEST 2013


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.


# 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'

Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list