Python's equivalent of .Net's sealed class -
does python have similar sealed class? believe it's known final class, in java.
in other words, in python, can mark class can never inherited or expanded upon? did python ever considered having such feature? why?
disclaimers
trying understand why sealed classes exist. answer here (and in many, many, many, many, many, really many other places) did not satisfy me @ all, i'm trying different angle. please, avoid theoretical answers question, , focus on title! or, if you'd insist, @ least please give one , practical example of sealed class in csharp, pointing break big time if unsealed.
i'm no expert in either language, know bit of both. yesterday while coding on csharp got know existence of sealed classes. , i'm wondering if python has equivalent that. believe there reason existence, i'm not getting it.
you can use metaclass prevent subclassing:
class final(type): def __new__(cls, name, bases, classdict): b in bases: if isinstance(b, final): raise typeerror("type '{0}' not acceptable base type".format(b.__name__)) return type.__new__(cls, name, bases, dict(classdict)) class foo: __metaclass__ = final class bar(foo): pass gives:
>>> class bar(foo): ... pass ... traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 5, in __new__ typeerror: type 'foo' not acceptable base type the __metaclass__ = final line makes foo class 'sealed'.
note you'd use sealed class in .net performance measure; since there won't subclassing methods can addressed directly. python method lookups work differently, , there no advantage or disadvantage, when comes method lookups, using metaclass above example.
Comments
Post a Comment