0

Is it possible to choose which base class to inherit from at the time of object creation? Basically, different objects of the same class will make the class inherit from different base classes depending on the initialization parameters.

Suppose I have 3 classes, ClassA, ClassB and ClassC:

class ClassA():
   pass
class ClassB():
   pass
class ClassC():
   def __init__(self,x):
      self.x=x

Depending on the value of x, ClassC should either inherit from ClassA or ClassB.

ClassCobj = ClassC(x=value)
# if value<10, ClassC should inherit from ClassA
# if value>10, ClassC should inherit from ClassB
  • I'm not sure exactly how to do it, but I have a few suggestions you can look up: 1. Have C inherit both A and B (look up multiple parent classes) and define attributes and methods to access from one class or the other depending on some attribute of the objects. 2. Perhaps by having both A and B inherit C instead, you could make it work. – Green05 Aug 13 '20 at 16:50
  • 1
    Please note that you shouldn't have deleted the question you asked 3 hours ago https://stackoverflow.com/questions/63396220/how-to-add-a-base-class-parent-class-to-a-class-in-python-depending-on-the-ini to ask the same again; I closed the first one as a duplicate of [Dynamic inheritance in Python](https://stackoverflow.com/questions/21060073/dynamic-inheritance-in-python), please explain how this doesn't answer your question. If it really didn't, I would have reopened it. – Thierry Lathuille Aug 13 '20 at 16:51
  • "Is it possible to choose which base class to inherit from at the time of object creation?" No, that doesn't make any sense. That is a sign that inheritance is not the pattern you are looking for. Just use composition. – juanpa.arrivillaga Aug 13 '20 at 17:24
  • @ThierryLathuille that's a **terrible** solution, the one in the linked duplicate. That creates a *different class* for *every instance*. No, the correct solution is *not to use inheritance at all*. Alternatively, there should be a factory function that chooses which class to instantiate, but not by dynamically creating the class in the function! – juanpa.arrivillaga Aug 13 '20 at 17:25

0 Answers0