multiple extensions to a class

David Fraser davidf at sjsoft.com
Fri Jul 9 12:05:09 CEST 2004


Humpty Dumpty wrote:
> Hello, I'm experimenting with different ways of extending a class (for a
> plug-ins framework for a GUI) with more than one extension when some of
> these extensions need to collaborate, but others mustn't know about each
> other.
> 
> I.e.,  if I have a class A, and I want to add a block of functionality, I
> can derive it into a B that adds that fucntionality. If I want to add more
> functionality, I can derive B into a C. But if I want to add a third bit of
> functionality D directly to A, such that D knows nothing about B or C, I
> won't be able to instantiate an object that has all three extensions, namely
> an "ABCD". It will either be an "ABC" or an "AD".
> 
> One possibility would be to define the extensions B,C and D as functions and
> add those functions to A with new.instancemethod. Any other ideas on how to
> do this? E.g. is it possible to *add* base classes to a class? I could add
> the extensions by adding them as base classes to A.
> 
> Thanks,
> Oliver
> 
> 
> 

I do a template class using a function:

def B(baseclass):
   class B(baseclass):
     def f(self, x, y):
       # do stuff
       super(B, self).f(x, y)
   return B

def C(baseclass):
   class C(baseclass):
     def f(self, x, y):
       # do stuff
       super(C, self).f(x, y)
   return C

extendedA = C(B(A))
extendedA.f(3,4)

I think you can find recipes like this in the Python cookbook...

David



More information about the Python-list mailing list