[Tutor] MutableString/Class variables

Albert-Jan Roskam fomcl at yahoo.com
Fri May 10 12:42:52 CEST 2013


>Subject: Re: [Tutor] MutableString/Class variables

>On 05/09/2013 09:16 AM, Albert-Jan Roskam wrote:
>>> 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.
>>
>> Hmmm, so is it fair to say that this is the OOP equivalent of 'nonlocal' in Python 3? It has meaning inside the entire scope of the class, not outside it, there not 'global'.
>>
>> Here's a modified version; in my previous attempts I messed up the arguments of super(). ;-) This feels better. But then again, I never *really* understood __new__ entirely.
>>
>> class MutableStr(str):
>>      def __init__(self, s):
>>          super(str, MutableStr).__init__(s)
>>          self.s = s
>>      def __repr__(self):
>>          return self.s
>>      def __str__(self):
>>          return self.s
>>      def __setitem__(self, key, item):
>>          self.s = self[:key] + item + self[key+1:]
>>
>> # produce results as intended
>> mstr = MutableStr("01234X678")
>> mstr[5] = "&"
>> print str(mstr)
>> print unicode(mstr)
>> mstr = MutableStr("01234X678")
>> mstr[8] = "&"
>> print str(mstr)
>> print unicode(mstr)
>>
>> # output:
>> 01234&678
>> 01234&678
>> 01234X67&
>> 01234X67&
>>
>>
>>
>
>That's all well and good as long as you only use those particular 
>methods.  But try:
>
>print "aaa" + mstr
>    #The changes you made to mstr have "vanished"
>
>print(type(mstr))
>mstr += "def"
>print(mstr)
>print(type(mstr))
>     #now it's no longer a MutablsStr


Hi Oscar, Dave, Alan,

Thanks. I agree that the conclusion is that inheriting from str is not a good idea (unless I'd reimplement each and every method, which would largely make inheritance useless). Using a bytearray as a basis instead is an ingenious alternative.

Regards,
Albert-Jan



More information about the Tutor mailing list