My Experiences Subclassing String

Fuzzyman michael at foord.net
Tue Jun 8 06:58:51 EDT 2004


"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message news:<510xc.52456$mQ4.51566 at fe2.texas.rr.com>...
[reluctant snip...]

> 
> class SpecialA(object):
>     pass
> 
> class A(object):
>     def __new__(cls,*args):
>         print cls,":",args
>         if len(args)>0 and args[0]==2:
>             return object.__new__(SpecialA)
>         return object.__new__(cls)
> 
> obj = A()
> print type(obj)
> obj = A(1)
> print type(obj)
> obj = A(1,"test")
> print type(obj)
> obj = A(2,"test")
> print type(obj)
> 
> gives the following output:
> 
> <class '__main__.A'> : ()
> <class '__main__.A'>
> <class '__main__.A'> : (1,)
> <class '__main__.A'>
> <class '__main__.A'> : (1, 'test')
> <class '__main__.A'>
> <class '__main__.A'> : (2, 'test')
> <class '__main__.SpecialA'>
> 
> 
> HTH,
> -- Paul

Thanks Paul, that was helpful and interesting.
I've posted the following correction to my blog :

Ok... so this is a correction to my post a couple of days ago about
subclassing the built in types (in python).

I *nearly* got it right. Because new is the 'factory method' for
creating new instances it is actually a static method and *doesn't*
receive a reference to self as the first instance... it receives a
reference to the class as the first argument. By convention in python
this is a variable named cls rather than self (which refers to the
instance itself). What it means is that the example I gave *works*
fine, but the terminology is slightly wrong...

See the docs on the new style classes unifying types and classes. Also
thanks to Paul McGuire on comp.lang.pyton for helping me with this.

My example ought to read :
class newstring(str):
    def __new__(cls, value, *args, **keywargs):
        return str.__new__(cls, value)
    def __init__(self, value, othervalue):
        self.othervalue = othervalue

See how the __new__ method collects all the other arguments (using the
*args and **keywargs collectors) but ignores them - they are rightly
dealt with by __init__. You *could* examine these other arguments in
__new__ and even return an object that is an instance of a different
class depending on the parameters - see the example Paul gives...

Get all that then ? :-)



More information about the Python-list mailing list