(Newbie) Restricting inherited methods to operate on element from same subclass
Duncan Booth
duncan.booth at invalid.invalid
Fri Mar 11 07:03:21 EST 2005
andy2o wrote:
> 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?
Assuming that A is a new-style class then if they have to be exactly the
same type compare the types:
def join(self, other):
if type(self) != type(other):
raise whatever
if the 'other' value can be a subclass of self:
def join(self, other):
if not isinstance(other, type(self)):
raise whatever
If A is an old-style class then you would have to compare the __class__
attribute: self.__class__ != other.__class__
More information about the Python-list
mailing list