spell method chaining?

Just van Rossum just at letterror.com
Fri Jun 8 13:57:19 EDT 2001


Remco Gerlich wrote:
> 
> Robin Becker <robin at jessikat.fsnet.co.uk> wrote in comp.lang.python:
> > I wish to create wrapped classes dynamically and have the wrapper class
> > refer to the base wrapee class methods.
> >
> > def gen(B):
> >     class W(B):
> >         def __init__(self):
> >             B.__init__(self)
> >     return W
> >
> > this works if nested scopes is on so that the reference to B in the
> > __init__ refers to the argument of gen, but it fails without it unless B
> > happens to be a global. I thought of using self.__class__.__bases__[0]
> > to refer to the dynamic base B, but then that fails if I use the
> > resultant class as a base class.
> >
> > ie if I try
> >
> > def gen(B):
> >     class W(B):
> >         def __init__(self):
> >             self.__class__bases__.__init__(self)
> >     return W
> >
> > I get trouble (infinite looping) with gen(gen(B))()
> >
> > What is the correct way for dynamic classes to refer to their immediate
> > base class methods to allow method chaining etc.
> 
> Usually you know that the base class is called eg Klass, and you simply call
> that. In this case I think you have to store it inside the class manually,
> like this:
> 
> def gen(B):
>    class W(B):
>       def __init__(self):
>          self.__base.__init__(self)
>    W._W__base = B
>    return W
> 
> (not the automatic 'name munging' the self.__base does, this way the
> attribute is somewhat protected from classes inheriting it)

You can avoid that by spelling it like this:

def gen(B):
   class W(B):
      __base = B
      def __init__(self):
         self.__base.__init__(self)
   return W

Just



More information about the Python-list mailing list