Where does str class represent its data?

James Stroud jstroud at mbi.ucla.edu
Fri Jul 13 01:27:48 CEST 2007

ChrisEdgemon at gmail.com wrote:
> I guess I don't understand what benefits come from using
> UserString instead of just str.

I hit send without remembering to include this kind of example:

from UserString import UserString as UserString
class MyString(UserString):
   def __init__(self, astr):
     UserString.__init__(self, astr)
     self.history = [astr]
   def update(self):
     if self.history[-1] != self.data:
   def fix_ms(self):
     self.data = self.data.replace('m', 'f')
   def fix_whitespace(self):
     self.data = "".join(c if c not in string.whitespace else '-'
                           for c in self.data.strip())

Now, you have a record of the history of the string, which may help you 

py> s = MyString('mail man')
py> s
'fail fan'
py> s.data
'fail fan'
py> s.history
['mail man','fail fan']
py> s.fix_whitespace()
py> s
py> s.history()
['mail man', 'fail fan', 'fail-fan']

A history of a str or instances or its subclasses make no sense because 
str is immutable. You may or may not want a history (I just made up this 
use case), but hopefully you see the utility in using regular classes 
for complex behavior instead of forcing an immutable built in type to do 


James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095


More information about the Python-list mailing list