oop - Dynamically instantiating child classes with different constructor parameters in Python -
suppose have python 2.7 code maintains list of options. parsing options, code can determine child class of complicated inheritance tree instantiate next. however, different child classes have different constructors take different parameter numbers. find myself writing code this:
childclassstr = get_child_class(currentoptiondict) childclass = getattr(importlib.import_module("meow"), childclassstr) # necessary parameters available @ point if childclass == class1: classinstance = childclass(param3, param4) elif childclass == class2: classinstance = childclass(param2, param3, param4) else: classinstance = childclass(param1, param2, param3, param4)
i realize not way handle this. there accepted way of doing instantiation? should dynamically build parameter list avoid if else statements , write like:
childclassstr = get_child_class(currentoptiondict) childclass = getattr(importlib.import_module("meow"), childclassstr) paramlist = assemble_class_params(childclass) classinstance = childclass(*paramlist)
or there cleaner way this? each child class supports different functionality; put them in inheritance tree avoid duplicating methods shared between subsets of child classes.
Comments
Post a Comment