Final classes like in java???

Jeremy Hylton jeremy at cnri.reston.va.us
Tue Nov 16 15:19:56 EST 1999


Arinte writes:
>> Is there a way you can define your python class to be final or
>> not able to be inherited from?

Fred writes:
>  Not guaranteed, but this should be good enough:
[see FinalClass below]

This doesn't really work.

>>> class FinalClass:
...     def __init__(self):
...         if self.__class__ is not FinalClass:
...             raise SomeError, "you can't subclass from me!"
... 
>>> class OhYeah(FinalClass):
...     def __init__(self):
...             pass
... 
>>> inst = OhYeah()
>>> isinstance(inst, FinalClass)

The FinalClass mechanism only makes it more inconvenient to create a
derived class.  The derived class must not call the __init__ of the
FinalClass.  If the FinalClass.__init__ doesn't do anything
significant, then it doesn't matter.  If the FinalClass.__init__ does
any non-trivial work, then the creator of the derived class needs to
do some cut-and-paste.

Jeremy






More information about the Python-list mailing list