A generic question: idiom for a paramterized base class?

Jonathan Hogg jonathan at onegoodidea.com
Fri Aug 2 00:38:03 CEST 2002


On 1/8/2002 10:11, in article
918bc22f.0208010111.23b016f6 at posting.google.com, "Donnal Walter"
<donnal at donnal.net> wrote:

> You are welcome. I am glad my suggestion proved helpful. But it seems
> to me that you are still trying to make things too complicated.
[...]
> Try this:
> 
> ###########################################
> class AbstractBase(object):
>    def __iadd__(self,other):
>        return self.TAdd(self,other)
>    def __add__(self,r):
>        return AbstractBase.__iadd__(self,r)
>    def __radd__(self,l):
>        return AbstractBase.__iadd__(l,self)
>    class TAdd(object): pass
> 
> class TNode1(AbstractBase):
> 
>    def __init__(self):
>        print "TNode1 instance"
> 
>    class TAdd(AbstractBase):
>        def __init__(self,l,r):
>            print "TAdd1 instance"
> 
> class TNode2(AbstractBase):
> 
>    def __init__(self):
>        print "TNode2 instance"
> 
>    class TAdd(AbstractBase):
>        def __init__(self,l,r):
>            print "TAdd2 instance"
> ###########################################

I'm afraid I don't think this will work.

% python -i TNode.py
>>> x = TNode1()
TNode1 instance
>>> y = TNode1()
TNode1 instance
>>> z = TNode1()
TNode1 instance
>>> x + y
TAdd1 instance
<__main__.TAdd object at 0x41c2b0>
>>> _ + z
<__main__.TAdd object at 0x41c930>
>>> 

Spot the missing call to the TNode1.TAdd constructor - that final TAdd is an
AbstractBase.TAdd.

I fear the solution is much more subtle. Though it's too late at night for
me to work it out, so I'll leave it as an exercise for some other reader ;-)

-try-Haskell's-parameterised-type-classes-;)-ly y'rs,

Jonathan




More information about the Python-list mailing list