Dynamic Inheritance is useful when you need to instantiate an object whose base class is only known at the time of instantiation.
For instance, I have a few different sequences:
And I want to instantiate an object that inherits the same class as one of the above input sequences. Unfortunately, I can’t know which sequence I will inherit from until the program is about to instantiate my object.
Rather than answering the question outright, this post will explain how dynamic inheritance works by example, but will leave the particular implementation of this problem to the reader. So\u2026 how can one dynamically inherit a class at time of instantiation?
One option is to define a factory function and a nested class definition to dynamically build and return a class:
Taking this a step further, you can return an instance that dynamically inherits a class type:
Which leads us to implement a MixIn: (This means that the cls will have all its methods + the methods in the mixin at its disposal. Super useful!)
This is how you would add multiple mixins at once: (Note that the following example doesn’t work when the underlying C structure for each class type is different).
Or you can pass in an instance and let your NewClass inherit the same type that the instance is.
As you can see, there are several variations of saying, more or less, the same thing. The above code shows you how to mash classes together using inheritance. The approach of using a nested class inside a function isn’t the only approach. Python’s type() builtin provides really cool builtin ways of doing this:
The builtin, type, can also make class objects dynamically:
For further details, you might also want to checkout the new method. And python metaprogramming