Inherit dynamic object in python -


i want create sub class "sub()" can inherit either object "a(object)" or object "b(object)".

the following works this:

class a(object):     def __init__(self):         print "class inherited"   class b(object):     def __init__(self):         print "class b inherited"   class sub(a if inh==a else b):     def __init__(self,inh):         if inh==a:             a.__init__(self)         else:             b.__init__(self) 

however, "inh" not defined parameter when construct "sub()". want able construct "sub()" argument "inh" initialize either "a(object)" or "b(object)".

so that:

my_object = sub(inh = a) 

will give me:

class inherited 

and that:

my_object = sub(inh = b) 

will give me

class b inherited 

my problem is, how pass "inh" constructor "sub()" can choose right object inherit?

immortal's solution, while right, has drawback: each call sub() yield new class, things isinstance() or class identity test break. solution keep mapping of created classes:

_clsmap = {}  def sub(base, *args, **kw):     if base not in _clsmap:         class sub(base):             def __init__(self, *args, **kw):                 super(sub, self).__init__(*args, **kw)     _clsmap[base] = sub     return _clsmap[base](*args, **kw) 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -