Python dynamic inheritance

Say I have two different class implementations

class ParentA: def initialize(self): pass def some_event(self): pass def order(self, value): # handle order in some way for Parent A class ParentB: def initialize(self): pass def some_event(self): pass def order(self, value): # handle order in another for Parent B 

How can I dynamically allow a third class to inherit from ParentA or ParentB based on something like this?

 class MyCode: def initialize(self): self.initial_value = 1 def some_event(self): # handle event order(self.initial_value) # let MyCode inherit from ParentA and run run(my_code, ParentA) 
+15
python inheritance
Jan 11 '14 at 8:08
source share
2 answers

Just save the object class in a variable (in the example below, it's called base ) and use the variable in the base class specification of your class statement.

 def get_my_code(base): class MyCode(base): def initialize(self): ... return MyCode my_code = get_my_code(ParentA) 
+34
Jan 11 '14 at 8:11
source share

Alternatively, you can use type builtin. As called, it takes arguments: name, bases, dct (in its simplest form).

 def initialize(self): self.initial_value = 1 def some_event(self): # handle event order(self.initial_value) subclass_body_dict = { "initialize": initialize, "some_event": some_event } base_class = ParentA # or ParentB, as you wish MyCode = type("MyCode", (base_class, ), subclass_body_dict) 

This is more explicit than the snx2 solution, but still - I like its way better.

PS. of course, you do not need to store base_class or subclass_body_dict, you can build these values ​​in type() , for example:

 MyCode = type("MyCode", (ParentA, ), { "initialize": initialize, "some_event": some_event }) 
+4
Jan 11 '14 at 11:49
source share



All Articles