A generic question: idiom for a paramterized base class?

Blair Hall b.hall at irl.cri.nz
Thu Aug 1 02:30:47 CEST 2002


Thanks Donnal,

Your idea seems to provide me with the following solution.
I have split your code into two modules and added a class:

############### DonnalBase.py
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

and

####### Donnal.py
from DonnalBase import AbstractBase

class MyClass1(object,AbstractBase):
    # One type of TAdd:
    class TAdd(AbstractBase):
        def __init__(self,l,r):
            print "TAdd instance 1"

class TNode(object,MyClass1):
    def __init__(self):
        print "TNode instance"

#######################
You see that I need 'MyClass' to act as a base for a
number of classes (like TNode). This seems to work:

>>> x = Donnal.TNode()
TNode instance
>>> y = Donnal.TNode()
TNode instance
>>> t = x + y
TAdd instance 1


Thanks

Blair

Donnal Walter wrote:

>

...snip...

> Does this do what you want?
>
> ##################################################
> 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 MyClass1(AbstractBase):
>
>     # One type of TAdd:
>     class TAdd(AbstractBase):
>         def __init__(self,l,r):
>             print "TAdd instance 1"
>
> class MyClass2(AbstractBase):
>
>     # Another type of TAdd:
>     class TAdd(AbstractBase):
>         def __init__(self,l,r):
>             print "TAdd instance 2"
> ##################################################
>
> >>> x = MyClass1()
> >>> y = MyClass2()
> >>> t = x + y
> TAdd instance 1
> >>> u = y + x
> TAdd instance 2
>
> Donnal Walter
> Arkansas Children's Hospital




More information about the Python-list mailing list