A generic question: idiom for a paramterized base class?

Donnal Walter donnal at donnal.net
Thu Aug 1 05:11:53 EDT 2002


Blair Hall <b.hall at irl.cri.nz> wrote:
> Thanks Donnal,
> 
> Your idea seems to provide me with the following solution.
> I have split your code into two modules and added a class:
>
 
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.

1. You shouldn't need to create two separate modules (unless you just
want to). It works fine to have all the definitions in the same
module.

2. You don't need to include "object" as a base for all class
definitions. Since AbstractBase inherits from object, all derived
classes do so automatically.

3. If I understand your original posting correctly, each different
subclass (such as TNode) needs its own (different) definitionof the
TAdd method. If that is the case, each subclass should inherit
*directly* from AbstractBase. In other words, MyClass is not
necessary.

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"
###########################################
Then:
>>> x = TNode1()
TNode1 instance
>>> y = TNode2()
TNode2 instance
>>> t = x + y
TAdd1 instance
>>> u = y + x
TAdd2 instance
>>>

Donnal Walter
Arkansas Children's Hospital



More information about the Python-list mailing list