Home > Software engineering >  Extending parent/children classes in python
Extending parent/children classes in python

Time:09-30

Is it possible in python for a nested class to extend its parent? Like this:

class Parent:
    class Child(Parent):
        pass

child = Parent.Child()

Is it possible to do this in the opposite direction? Like this:

class Parent(Child):
    class Child:
        pass

parent = Parent()

From what I know this is not possible, even with from __future__ import annotations. The best known way around this is just not to make nested classes.

Important: The purpose of this question is to make it clear if this is even possible in the python language. There is no "final goal", objectives to be accomplished with this approach or justification for it. Don't spam in the comments/answers about "how bad this code is".

CodePudding user response:

No and Yes.

No, because when you inherit from a class, that class must be defined before you can inherit from it. Neither of your code examples will work due to this.

Yes, because Python is a dynamic language and you can change (monkey-patch) the base classes even after defining them:

class Temp:
    pass

# example 1
class Parent:
    class Child(Temp):
        pass

Parent.Child.__bases__ = (Parent,)

# example 2
class Parent(Temp):
    class Child:
        pass

Parent.__bases__ = (Parent.Child,)

Why use the Temp class?

Classes automatically inherit from object. Due to a bug (https://bugs.python.org/issue672115), we cannot change __bases__ if a class inherits from object. Hence, we inherit from a temporary (Temp) class to avoid that issue.

  • Related