Designing for Inheritance

Don O'Donnell donod at home.com
Thu Dec 13 02:13:32 EST 2001


"nspies.geo" wrote:

<cut>
> 
> The problem is thus: how do I design the base class so that it will
> create an extracted object of the correct type, even if it's been
> inherited?  It may well be that the inherited class needs to wrap the
> base class function, but I do not wish to re-write the function in
> every base class.
> 
> Here it is in code.
> 
> --
> 
> class BaseAlignment:
>    def extractx(self, x):
>       extraction = BaseAlignment()
>       extraction = self.data[0:x]
> 
>       return extraction
> 
> class InheritedAlignment(BaseAlignment):
>    def extractx(self, x):
>       BaseAlignment.extractx(self, x)
> 
>       #do something more here...
> 
>       return extraction
> 
> --
> 
> The problem is that the return value of extractx from
> InheritedAlignment is a BaseAlignment.... 

<cut>

> Any hints?

Sure.  Instead of using a fixed identifier for the base class name, 
use the variable self.__class__ instead:

class BaseAlignment:
    def extractx(self, x):
        extraction = self.__class__()
        ...

Now if self is actually an instance of subclass InheritedAlignment,
extraction will also be an instance of subclass InheritedAlignment.
> 
> Thanks,

No problem.  Hope this is what you are looking for.

Cheers,
Don



More information about the Python-list mailing list