i need to do something like this:
class Base1:
def __init__(self, uniform_params):
pass
class Base2:
def __init__(self, uniform_params):
pass
class DynamicDerive(self, dynamicspec, uniform_params):
kls = dynamicspec.kls
kls.__init__self, uniform_params)
spec = SomeSpecificationObject()
spec.kls = Base1
x = DynamicDerive(spec, uniform_params)
spec2 = SomeSpecificationObject()
spec2.kls = Base2
y = DynamicDerive(spec2, some_more_uniform_params)
the parameters to Base1 and Base2 are uniform and consistent. the requirement is to pass in the class that DynamicDerive is to derive from at instance creation time.
the alternative is "simple": create DynamicDerive1(Base1), DynamicDerive2(Base2), except unfortunately:
- the class DynamicDerive is used in hundreds of places.
- there is no way to predict what future users will pass in, here. users may create a Base3, Base4 etc.
so a cut/paste option of creating entire swathes of hundreds of identical classes, which merely change the name of the base class, is just not an option.
hypothetically this could be solved through a "redirection" API, where a special class does this:
class Base:
def __init__(self, redirectorkls, uniform_args):
self.redir = redirectorkls(uniformargs)
def fn1(self, *args, **kwargs):
return self.redir.fn1(*args, **kwargs)
def fn2(self, *args, **kwargs):
return self.redir.fn2(*args, **kwargs)
...
...
however although it will work, that entirely defeats the object of the exercise. there has to be a way to do this that involves meta-programming (meta-classes).
looking up metaclass programming tutorials, unfortunately, all show how to create classes from outside of the constructor, whereas what is needed above is for the metaclass to be created inside the constructor.
anyone have any clues?
[update] - i need to then be able to further derive from DynamicDerive. GreenCloakGuy kindly answered by providing a function that would do the task, however it is not possible to derive classes from functions.
class DerivedFromDynamicDerive(DynamicDerive):
def __init__(self, dynamicspec, nonuniformparams, uniform_params):
self.nonuniformparams = nonuniformparams
DynamicDerive.__init__(self, dynamicspec, uniform_params)
(note: as this is actual libre code, the place where this is required is here: https://git.libre-riscv.org/?p=ieee754fpu.git;a=blob;f=src/ieee754/fpadd/addstages.py;h=2bc23df0dabf89f8a4e194d5e573a88d5d740d0e;hb=78cbe8c5131a84426a3cad4b0b3ed4ab7da49844#l19
SimpleHandShake needs to be dynamically replaced in around 40 places, where users of this IEEE754 compliant RTL may specify the class that they wish to use. this is just of over 50 classes that need this capability).