1

In case I would like dynamically add a base class to child class but I don't know what classes will be

which option should I use?

# first_file.py

# Option 1
def add_base(clazz, new_parent_class):
   bases = tuple(list(clazz.__bases__) + [new_parent_class])
   clazz.__bases__ = bases
   return clazz

# Option 2
def add_base(clazz, new_parent_class):
   bases = tuple(list(clazz.__bases__) + [new_parent_class])
   clazz = type(clazz.__name__, bases, dict(clazz.__dict__))
   return clazz
# second_file.py

class OtherClass(object # or any other class #)
   def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
 class MyClass(object # or any other class #)
   def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
# fourth_file.py

from first_file import add_base
from second_file import OtherClass
from third_file import MyClass

new_class = add_base(OtherClass, MyClass)
ins = new_class()
3
  • I had the same question. Look here to get the idea of it: stackoverflow.com/questions/62050496/… Commented Jun 10, 2020 at 15:51
  • This sounds like a bad idea overall: code works generally better with fixed classes. It sounds like your implementation requires some different type of structure that can fulfill the roles that you want these dynamic subclasses to fill. Commented Jun 10, 2020 at 15:52
  • your classes should be concrete. if you dont know what classes you might need or want then maybe relook at your design Commented Jun 10, 2020 at 15:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.