On 05/09/2013 09:16 AM, Albert-Jan Roskam wrote:


Subject: Re: [Tutor] MutableString/Class variables

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


--
DaveA
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to