Possible Duplicate:
Final classes in Python 3.x- something Guido isn't telling me?
I was watching a talk (How to design a good API and why it matters) in which it was said, literally, "design and document for inheritance, else prohibit it". The talk was using Java as an example, where there's the 'final' keyword for prohibiting subclassing. Is it possible to prohibit subclassing in Python? If yes, it'd be great to see an example... Thanks.
The way to "avoid" inheritance here would be to rename _private_var and make it a class-private name. i.e. __private_var . If you do this, running your code will cause an AttributeError: 'Child' object has no attribute '_Parent__private_var' (note the _Parent prefix automatically added).
To prevent inheritance, use the keyword "final" when creating the class. The designers of the String class realized that it was not a candidate for inheritance and have prevented it from being extended.
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
Method Resolution Order in Python In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching the same class twice.
There is no Python keyword for this - it is not Pythonic.
Whether a class can be subclassed is determined by a flag called Py_TPFLAGS_BASETYPE which can be set via the C API.
This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a “final” class in Java).
You can however emulate the behaviour using only Python code if you wish:
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
Source
In my opinion, classes should generally not have any subclassing restrictions at all. I would like to suggest the third option: Add a comment in your class' documentation that states that the class is not meant to be subclassed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With