(Newbie) Restricting inherited methods to operate on element from same subclass
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Fri Mar 11 15:52:48 EST 2005
andy2o a écrit :
> Hi all,
>
> Sorry if the post's title is confusing... I'll explain:
>
> I have a class, called A say, and N>1 subclasses of A, called
> A1, A2, A3, ..., AN say.
>
> Instances of each subclass can sensibly be joined together with other
> instances of the *same subclass*. The syntax of the join method is
> identical for each of the N subclasses, so it would make sense to
> implement a *single* method called join in the toplevel class A, and
> then do:
>
> a = A1()
> b = A1()
> a.join(b) #I want the join method to be inherited from class A
>
> d = A2()
> e = A2()
> d.join(e)
>
> But I want to raise an exception if my code finds:
>
> f = A1()
> g = A2()
> f.join(g) #should raise exception, as cannot join an
> #instance of A1 to an instance of A2.
>
> How can I verify in a method defined in class A that the subclasses I
> am joining are exactly the same? Or is there a design flaw here I
> haven't spotted that makes this a bad idea? Or do I need to code N
> join methods?
You've already got the technical answer. About a possible design flaw,
it would seem to me that restricting the join() operation on specific
subclasses breaks the LSP. OTOH, Python being dynamically typed,
inheritence is merely an implementation detail, so that may not be such
a big deal after all... Anyway, you may want to document this point to
make it clear for the next person that'll have to work this code.
My 2 cents
More information about the Python-list
mailing list