Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I prohibit class inheritance? [duplicate]

Tags:

python

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.

like image 212
aeter Avatar asked Oct 16 '10 12:10

aeter


People also ask

How do you prevent a class from inheritance in Python?

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).

How do you restrict inheritance of a class?

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.

What does super () do in Python?

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.

How does Python resolve multiple inheritance?

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.


2 Answers

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

like image 95
Mark Byers Avatar answered Sep 27 '22 23:09

Mark Byers


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.

like image 30
steinar Avatar answered Sep 28 '22 00:09

steinar