In Python, how can I prevent class inheritance?

Possible duplicate:
The final classes in Python 3.x are something that Guido doesn't tell me?

I watched the conversation ( How to create a good API and why it is important ), which said literally β€œdesign” and a document for inheritance, otherwise prohibit it. ”The conversation used Java as an example where there is a final keyword to prohibit subclassing. prohibit subclassing in Python? If yes, it would be great to see an example ... Thanks.

+4
source share
2 answers

There is no Python keyword for this - it is not Pythonic.

Is the class defined by a subclass using a flag called Py_TPFLAGS_BASETYPE , which can be set via API C.

This bit is set when a type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to the "final" class in Java).

However, you can emulate the behavior using only Python code if you want:

class Final(type): def __new__(cls, name, bases, classdict): for b in bases: if isinstance(b, Final): raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__)) return type.__new__(cls, name, bases, dict(classdict)) class C(metaclass=Final): pass class D(C): pass 

A source

+7
source

In my opinion, classes should not have any restrictions on subclasses at all. I would like to suggest a third option: Add a comment to the documentation of your class, which states that the class is not intended to be a subclass.

+6
source

Source: https://habr.com/ru/post/1204103/


All Articles