subclassing Python types

James Stroud jstroud at mbi.ucla.edu
Thu Aug 30 15:42:19 EDT 2007


zzbbaadd at aol.com wrote:
> I don't know what name I would use to call a method:
> 
> 
> class MyString(str):
>     def __init__(strInput):
>        ????? = strInput

You need to read up on subclassing builtin types and/or describe what 
you want to achieve. str is an immutable type, and so you must return an 
instance from __new__. Read this:

   http://www.python.org/download/releases/2.2.3/descrintro/

And here is an example that might get you started (assuming you really 
want to do this):

class StupidDefaultString(str):
   default = "I'm a Default!"
   success = "42"
   error = "Not a default, don't bother."
   def __new__(cls, arg=None):
     if arg is None:
       arg = cls.default
     return str.__new__(cls, arg)
   def __str__(self):
     if self == self.default:
       return self.success
     else:
       return self.error

py> s = StupidDefaultString('Bob')
py> s
'Bob'
py> print s
Not a default, don't bother.
py> s = StupidDefaultString()
py> s
"I'm a Default!"
py> print s
42


James

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

http://www.jamesstroud.com/



More information about the Python-list mailing list