Unified Type/class
Alex Martelli
aleax at aleax.it
Sun Jan 27 10:54:16 EST 2002
Pedro Rodriguez wrote:
...
>> I'm not sure that it's a problem in Python that the capability is
>> restricted to classes coded in Python. In cases where you need to
...
> But I think that you can even restrict this capability on classes by
> providing the apropriate metaclass, something like 'FinalType' with
> a semantic close to 'final' keyword in Java.
Sure -- piece of cake [warning, untested code]:
class finalType(type):
def __init__(self, name, bases, classdict):
if bases: raise TypeError, "cannot subclass Final type"
type.__init__(self, name, bases, classdict)
Just use __metaclass__=finalType in a class body, and that class
won't be subclassable (except by further metaclass tweaks...:-).
As above written, the class itself also won't be able to subclass
any other, but that's easy to remedy too, e.g.:
class finalType2(type):
def __init__(self, name, bases, classdict):
if bases and isinstance(bases[0], finalType2):
raise TypeError, "cannot subclass Final type [2]"
type.__init__(self, name, bases, classdict)
Alex
More information about the Python-list
mailing list