python - how to dynamically generate a subclass in a function? -
i'm attempting write function creates new subclass named string gets passed argument. don't know tools best this, gave shot in code below , managed make subclass named "x", instead of "mysubclass" intended. how can write function correctly?
class mysuperclass: def __init__(self,attribute1): self.attribute1 = attribute1 def makenewclass(x): class x(mysuperclass): def __init__(self,attribute1,attribute2): self.attribute2 = attribute2 x = "mysubclass" makenewclass(x) myinstance = mysubclass(1,2)
the safest , easiest way use type
builtin function. takes optional second argument (tuple of base classes), , third argument (dict of functions). recommendation following:
def makenewclass(x): def init(self,attribute1,attribute2): # make sure call base class constructor here self.attribute2 = attribute2 # make new type , return return type(x, (mysuperclass,), {'__init__': init}) x = "mysubclass" mysubclass = makenewclass(x)
you need populate third argument's dict want new class have. it's generating classes , want push them list, names won't matter. don't know use case though.
alternatively access globals
, put new class instead. strangely dynamic way generate classes, best way can think of seem want.
def makenewclass(x): def init(self,attribute1,attribute2): # make sure call base class constructor here self.attribute2 = attribute2 globals()[x] = type(x, (mysuperclass,), {'__init__': init})
Comments
Post a Comment