design question

Alex Martelli aleax at aleax.it
Thu Sep 26 14:43:16 EDT 2002


Gonçalo Rodrigues wrote:
        ...
>   Class1
>      |
>      |
>   Class2
> 
> Where the dashed line means a parent-child relationship. Now what I want
> is something like
> 
>   Wrapper1
>      |
>      |
>   Wrapper2
> 
> where Wrapper1 (Wrapper2) wraps Class1(Class2) and the inheritance
> reltionships between the several wrappers mirror those of the classes
> they wrap -- but as I said, the protocol that the wrappers have can be
> substantially different from the classes they wrap.
> 
> Leaving aside the question of the usefulness of doing all this, I would
> like to ask how would you proceed? Making Wrapper derive from Class is
> stupid since their protocols can differ widely and I would end up with
> lots of diamonds in the inheritance graph. On the other hand I could
> just do:
> 
> class Wrapper1(object)
>     def __init__(self, <more args>):
>         self.__wrap = Class1()
>         <more initialization code>
> 
> But then if I did the same with Wrapper2, it would be at least quirky
> since it inherits from Wrapper1 but it wraps Class1 <scratches head in
> puzzled bewilderment>

Don't use __wrap as it interferes with communication between Wrapper1
and Wrapper2; use _wrap, with a single underscore, so that such
communication within your own hierarchy of wrappers is unimpeded,
whild (by convention) you're still communicating to the outside
world that this is an internal implementation detail.

Declare all your wrapper's __init__ method with a similarly named
optional argument, a tuple that determines what factory callable
to call to get the object to be wrapped:

class Wrapper1(object):

    def __init__(self, <whatever args>, _wrap=(Class1,)):
        self._wrap = _wrap[0](*_wrap[1:])
        <more init code>


class Wrapper2(Wrapper1):

    def __init__(self, <whatever args>, _wrap=(Class2,)):
        super(Wrapper2, self).__init__(<whatever>, _wrap=_wrap)
        <more init code>


Alex




More information about the Python-list mailing list